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.

[TypeScript] The Basics of Generics in TypeScript的更多相关文章

  1. 玩转TypeScript(引言&文章目录) --初看TypeScript.

    JavaScript过去一直被当作一种玩具语言存在,直到2005年以后,这门语言又开始活跃并可以说是火爆,而且随着浏览器版本的不断升级和完善,各种DOM之间的兼容性已经渐渐的被各种技术解决了,比如经典 ...

  2. electron教程(番外篇二): 使用TypeScript版本的electron, VSCode调试TypeScript, TS版本的ESLint

    我的electron教程系列 electron教程(一): electron的安装和项目的创建 electron教程(番外篇一): 开发环境及插件, VSCode调试, ESLint + Google ...

  3. [Typescript] Introduction to Generics in Typescript

    If Typescript is the first language in which you've encountered generics, the concept can be quite d ...

  4. [Typescript] Generics using TypeScript

    In this lesson we cover the key reason why programming languages need generics. We then show how use ...

  5. TypeScript完全解读(26课时)_6.TypeScript完全解读-泛型

    6.TypeScript完全解读-泛型 创建实例ts文件generics.ts 在index.ts内引入 fill是填充数组,创建的数组的元素数是times,填充的值就是接收的value的值 这里传入 ...

  6. [TypeScript] 1. Catching JavaScript Mistakes with TypeScript

    The TypeScript compiler is a powerful tool which catches mistakes even in vanilla JavaScript. Try it ...

  7. [TypeScript] Work with DOM Elements in TypeScript using Type Assertions

    The DOM can be a bit tricky when it comes to typing. You never really know exactly what you're going ...

  8. [TypeScript] Dynamically initialize class properties using TypeScript decorators

    Decorators are a powerful feature of TypeScript that allow for efficient and readable abstractions w ...

  9. TypeScript完全解读(26课时)_1.TypeScript完全解读-开发环境搭建

    1.TypeScript完全解读-开发环境搭建 初始化项目 手动创建文件夹 D:\MyDemos\tsDemo\client-demo 用VSCode打开 npm init:初始化项目 然后我们的项目 ...

随机推荐

  1. 图片的title属性和alt属性的区别

    在前端开发中,经常遇到有人在问图片的alt属性和title属性的区别,这是因为很多人对于alt属性和title属性没有彻底搞明白,今天零度给大家分析分析. title属性 首先,来看一下什么是titl ...

  2. Spring Cloud Netflix Eureka client源码分析

    1.client端 EurekaClient提供三个功能: EurekaClient API contracts are:* - provide the ability to get Instance ...

  3. SKU=Stock Keeping Unit(库存量单位)。即库存进出计量的单位,可以是以件,盒,托盘等为单位

    SKU=Stock Keeping Unit(库存量单位).即库存进出计量的单位,可以是以件,盒,托盘等为单位.SKU这是对于大型连锁超市DC(配送中心)物流管理的一个必要的方法.现在已经被引申为产品 ...

  4. 经典的横线中间文字css布局---flex布局

    html: <div class="title"> <div class="line"></div> <div cla ...

  5. 执行异步UI更新

    异步更新UI的几种方法①.使用Control.Invoke方式来更新数据                     foreach (DataGridViewRow dgvr in this.dgv_s ...

  6. UVALive 5292 Critical Links

    Critical Links Time Limit: 3000ms Memory Limit: 131072KB This problem will be judged on UVALive. Ori ...

  7. 洛谷 P1553 数字反转(升级版)

    P1553 数字反转(升级版) 题目描述 给定一个数,请将该数各个位上数字反转得到一个新数. 这次与NOIp2011普及组第一题不同的是:这个数可以是小数,分数,百分数,整数.整数反转是将所有数位对调 ...

  8. JS-网页中分页栏

    原理 三部分 我给分页栏分成了3部分 上一页:调用prePage()函数 下一页:调用nextPage()函数 带有数字标识的部,调用skipPage()函数 prePage函数 function p ...

  9. 5.使用SOAP的XML消息传递

    转自:https://blog.csdn.net/u014066037/article/details/51724658 使用SOAP的XML消息传递的简易流程图: 详细步骤如下: (1)服务请求者的 ...

  10. POJ Fence Repair(优先队列)

    Fence Repair Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 51346   Accepted: 16857 De ...