zoukankan      html  css  js  c++  java
  • [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.

  • 相关阅读:
    阿里云高级技术专家周晶:基于融合与协同的边缘云原生体系实践
    Spring Boot Serverless 实战系列“架构篇” 首发 | 光速入门函数计算
    基于 EMR OLAP 的开源实时数仓解决方案之 ClickHouse 事务实现
    【ClickHouse 技术系列】 在 ClickHouse 中处理实时更新
    LeetCode_Two Sum
    LeetCode_ Remove Element
    LeetCode_Same Tree
    LeetCode_Symmetric Tree
    LeetCode_Path Sum
    LeetCode_Merge Sorted Array
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5961960.html
Copyright © 2011-2022 走看看