zoukankan      html  css  js  c++  java
  • [TypeScript] Generic Functions, class, Type Inference and Generics

    Generic Fucntion:

    For example we have a set of data and an function:

    interface HasName {
        name: string;
    }
    
    const heros: HasName[] = [
        {name: 'Jno'},
        {name: 'Miw'},
        {name: 'Ggr'},
        {name: 'Gew'},
        {name: 'Wfe'}
    ];
    
    function cloneArray(ary: any[]): any[] {
        return ary.slice(0);
    }
    
    const clones = cloneArray(heros);

    When we check the 'clones' type, you can see it is 'any[]'.

    To add more type information we can change the function:

    function cloneArray<T>(ary: T[]): T[] {
        return ary.slice(0);
    }

    Now we get 'clones' type as 'HasName[]'.

    Generic Class:

    class SuperCharacter {
        constructor(public name: string) {
    
        }
    }
    
    class Hero extends SuperCharacter {
    
    }
    
    class SuperTeam {
        constructor(public members: SuperCharacter[],
            public leader: SuperCharacter
        ) {
    
        }
    }
    
    const captainAmerica = new Hero('Captain America');
    const thor = new Hero('Thor');
    const ironMan = new Hero('IronMan');
    
    const avengers = new SuperTeam(
        [captainAmerica, thor, ironMan],
        captainAmerica
    );
    
    const members = avengers.members;

    If we check 'avengers' type is 'SuperTeam'. 'memebers' type is 'SuperCharacter[]'.

    To add more information to the types we can do:

    class SuperTeam<T> {
        constructor(public members: T[],
            public leader: T
        ) {
    
        }
    }

    Now the 'avengers' type is 'SuperTeam<Hero>' and 'members' type is 'Hero[]'.

    Now, let's say we have another class:

    class Villain extends SuperCharacter {
    
    }

    Have some members.

    const luthor = new Villain('Luthor');
    const bizarro = new Villain('Bizarro');
    const captainCold = new Villain('Captain Cold');
    
    const megaCrossoverTeam = new SuperTeam([
        captainAmerica, thor, ironMan, luthor,
        bizarro, captainCold
    ], captainAmerica);

    'megaCrossoverTeam' is type of 'SuperTeam<Hero | Villain>'.

    If we want to add some restrictions to the class, we can do:

    class SuperTeam<T extends SuperCharacter> {
        constructor(public members: T[],
            public leader: T
        ) {
    
        }
    }

    Then the example below will throw error:

    const avengers = new SuperTeam(
        [0, 1, 2],
        0
    );

    Because the type is number.

  • 相关阅读:
    javascript功能插件大集合
    基于Swiper插件的简单轮播图的实现
    LeetCode24. 两两交换链表中的节点
    530. 二叉搜索树的最小绝对差
    416. 分割等和子集
    GAN ——Generative Adversarial Network 理解与推导(一)
    面试题 02.08. 环路检测(返回环路开头节点)
    141.环形链表-LeetCode
    357. 计算各个位数不同的数字个数 ——LeetCode
    LSTM的理解
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8443574.html
Copyright © 2011-2022 走看看