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