typescript--泛型


// 普通接口里面有泛型函数, 接口里的函数是泛型函数
// 函数参数和函数返回类型,泛型函数在函数的括号前加 
// Array
interface TestObj1 {
    <T>(arg:T):T,
}
// 泛型函数
function testFunction1<T>(arg: T): T {
    return arg;
}
let usage1 : TestObj1 = testFunction1;


// 另一种写法
interface TestObj2 {
   b: <T>(arg:T) => T
}
function testFunction2<T>(arg: T): T {
    return arg;
}
let obj = { b: testFunction2}
let usage2 : TestObj2 =obj;



// 泛型接口
interface TestObj3<T> {
    <T>(arg:T):T,
}
function testFunction3<T>(arg: T): T {
    return arg;
}
let usage3 : TestObj3<number> = testFunction3;


// 泛型类
class TestObj4<T> {
    add!: (x:T, y:T) => T;
    zeroValue!:T;
    constructor() {}
}
let usage4 = new TestObj4<number>();
 usage4.add = (x:number, y: number) => x + y;
 usage4.zeroValue = 0;


 // 泛型约束
interface TestObj5 {
    length:number;
}
function testFunction5<T extends TestObj5>(arg: T): T {
    return arg;
}
//Error
testFunction5(2);  
// 一定要传规定的testObj5的结构,这个就、叫约束 
testFunction5({ length:2, value:2});  

可索引的类型

interface IndexInterfaceTest {
    [index: number]: string;
}
let indexUsage: IndexInterfaceTest = ['a', 'b'];
// 'a'
console.log(indexUsage[0]);
// 'b'
console.log(indexUsage[1]);
let indexUsage2: IndexInterfaceTest = {0: 'c',1: 'd'}
// 'c'
console.log(indexUsage2[0]);
// 'd'
console.log(indexUsage2[1]);

interface Obj {
    name: string;
    age: number;
}
interface IndexInterfaceTest2 {
    [index: string]: Array<Obj>;
}
let values:IndexInterfaceTest2 = {'student': [{name: 'lvxin', age: 18}], 'student2':[]}
// []
console.log(values['student2']);
// ['student', 'student2']
let attrs: Array<keyof IndexInterfaceTest2> = Object.keys(values);
console.log(attrs);

你可能感兴趣的:(TypeScript,typescript,javascript,前端)