[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.

原文地址:https://www.cnblogs.com/Answer1215/p/8443574.html

时间: 2024-11-06 07:49:44

[TypeScript] Generic Functions, class, Type Inference and Generics的相关文章

你不知道的JAVA系列一 Type Inference

在正式开讲之前先容许我说下写这篇文章的故事背景.前几天我们的production下的一个tool突然莫名其妙的报错,那部分功能已经很久没有改动过了,按理说是不应该出现问题的,代码在做反射调用method的时候出现了ClassCastException.我先是以为可能是什么小问题就把任务分给我同事了,他分析下来告诉我不知道什么问题,莫名其妙的就突然抛异常了:那找不到问题我们就只能怪JAVA Compiler了  原来最近我们做了一次JDK的升级,从7升级到了8,起先以为是reflect的Metho

[TypeScript] Union Types and Type Aliases in TypeScript

Sometimes we want our function arguments to be able to accept more than 1 type; e.g. a string or an array. This lesson will show us how to assign more than 1 type to a variable with Typescript union types and type aliases. type types = string | boole

[TypeScript] Use the never type to avoid code with dead ends using TypeScript

Example 1: A never stop while loop return a never type. function run(): never { while(true){ let foo = "bar"; } } Example 2: Never run If block const foo = 123; if(foo !== 123) { let bar: never = foo; } You can use this to do exhaustive checks i

[TypeScript] Define a function type

type DigitValidator = (char) => boolean; const numericValidator = (char) => /[0-9]{1}/.test(char); export const digitValidators: {[key: string]: DigitValidator} = { '9': numericValidator }; We can use 'type' keyword to define a function type. 'digit

Swift:Minimizing Annotation with Type Inference

许多程序猿更喜欢比如Python和Javascript这样的动态语言,因为这些语言并不要求程序猿为每个变量声明和管理它们的类型. 在大多数动态类型的语言里,变量可以是任何类型,而类型声明是可选的或者根本不允许. Objective-C采用了混合的处理方式:它需要类型声明,但是任何指向一个Objective-C类实例的变量(包括任何从NSObject派生出的类,但不能是所谓的原始类型,比如int,float等等)可以简单的声明为其类型为id,因此可以指向任何Objective-C实例类型. 甚至当

【转】如何评价 Apple 新推出的编程语言 Swift?

如何评价 Apple 新推出的编程语言 Swift? 原文地址:http://www.zhihu.com/question/24002984 评价:如果你会Objective-C,你不需要去看它. 如果问我这语言对普通开发者重要不重要,我说重要,可以明确告诉你这一点--它是Apple 在WWDC 向全世界推出的重磅语言我怎么能说它不重要?它降低了入门的门槛.使得大量的JS, Python, Ruby用户会使用Apple 的技术为其开发程序.它的作用,和Core Data, Interface B

[TypeScript] Define Custom Type Guard Functions in TypeScript

One aspect of control flow based type analysis is that the TypeScript compiler narrows the type of a variable within a type guard. This lesson explores how you can define functions and type predicates to create your own type guards similar to the Arr

寒城攻略:Listo 教你 25 天学会 Swift 语言 - 24 Generics

import Foundation //*********************************************************************************************** //1.Generics(泛型) //_______________________________________________________________________________________________ //介绍 //泛型代码可以让你写出根据

二十一、泛型 Generics

1.概述 泛型是Swift中最强大的特性之一,使用泛型可以写出灵活.可重用.干净.抽象的代码,并且避免代码重复.实际上在第一章中我们就接触到了泛型,Array 和 Dictionary 是泛型容器,可以存入任何类型. 2. 泛型所要解决的问题 The Problem That Generics Solve 下面定义了一个交换两个值的函数,它没有使用泛型特性: func swapTwoInts(inout a: Int, inout b: Int) { let temporaryA = a a =