It can be painful to write the same function repeatedly with different types. Typescript generics allow us to write 1 function and maintain whatever type(s) our function is given. This lesson covers syntax and a basic use case for Typescript generics.

We have a reusable function that pushes something into a collection, and then console logs the collection. We have two objects, and two arrays. We can just call the function with anything an array,

function pushSomethingIntoCollection(something, collection) {
collection.push(something);
console.log(collection);
} let jeanGrey = { name: "Jean Grey" };
let wolverine = { name: "Wolverine" }; let superHeroes = [jeanGrey];
let powers = ["telekinesis", "esp"]; pushSomethingIntoCollection("cool", superHeroes);
pushSomethingIntoCollection("adamantium claws", []);

but we're human and we make errors. What we want is to make sure we're pushing the right something, into the right array.

We can use a generic to tell the compiler, we're going to be using a specific type, but we're not going to tell you what that type is until the function is called. This is what a generic looks like. It doesn't matter what's between the angle brackets, as long as it makes sense to you.

function pushSomethingIntoCollection<T>(something: T, collection: T[]) 

Now if we do:

pushSomethingIntoCollection("meh", superHeroes);

IDE will show us error, because 'something: T' is string type, then collection should be array to string type.

But 'superHeros' is array of object type.

interface SuperHero {name: string;}

pushSomethingIntoCollection<SuperHero>("meh", superHeroes); //Error
pushSomethingIntoCollection<string>("adamantium claws", []); //OK

We can provide interface to tell IDE what generice type should be. So IDE can help to catch error.

最新文章

  1. vim vundle 安装Base16 Vim主题
  2. 解决oracle服务器重启之后连接报错的问题
  3. VS2012配置使用ICE通信接口
  4. PCIe 32GT/s 含义
  5. poj2387 初涉最短路
  6. Android工具包
  7. 利用if else来运行咱们结婚吧
  8. TensorFlow 深度学习笔记 Stochastic Optimization
  9. Jquery揭秘系列:谈谈bind,one,live,delegate,on事件及实现
  10. SVN记录使用过程中出现的错误(一)
  11. Bootstrap 图像
  12. NOIP2011-普及组复赛-第一题-数字反转
  13. 全局精确流量调度新思路-HttpDNS服务详解
  14. Git的本地仓库与GitHub的远程仓库
  15. 【转载】C#:使用双缓冲让界面绘制图形时避免闪烁
  16. 【ASP.NET MVC系列】浅谈ASP.NET 程序发布过程
  17. 类库中使用WPF 资源文件
  18. css笔记 - 张鑫旭css课程笔记之 absolute 篇
  19. Python 中的变量
  20. 转载:15个最受欢迎的Python开源框架

热门文章

  1. 2.Brackets安装及常用插件安装
  2. ssm框架的总结
  3. 抓包神器Fiddler之Https请求随心转
  4. [Python] List &amp; Object spread in Python
  5. Android基础新手教程——3.8 Gestures(手势)
  6. thinkphp内置标签简单讲解
  7. go reflect 调用方法
  8. Java 批量修改文件后缀
  9. 3.字符设备驱动------Poll机制
  10. java 并发原子性与易变性 来自thinking in java4 21.3.3