typescript范型

范型:支持不特定的类型,要求传入的参数和返回的参数保持一致。
1 基本例子

function identity(arg: T): T {
    return arg;
}
let output = identity("myString"); 
let output = identity("myString"); 

2 泛型变量

function loggingIdentity(arg: T[]): T[] {
    console.log(arg.length);  // Array has a .length, so no more error
    return arg;
}
// 也可以这样
function loggingIdentity(arg: Array): Array {
    console.log(arg.length);  // Array has a .length, so no more error
    return arg;
}
loggingIdentity(['2'])

3 泛型类

class GenericNumber {
    zeroValue: T;
    add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };

4 泛型约束

interface Lengthwise {
    length: number;
}
function loggingIdentity(arg: T): T {
    console.log(arg.length);  // Now we know it has a .length property, so no more error
    return arg;
}
loggingIdentity(3);  // Error, number doesn't have a .length property

5 范型接口

interface Fn{
    (value:T):T;
}
function print(value:T):T{

    return value;
}
const printData:Fn=print;  

你可能感兴趣的:(typescript范型)