在编译期间不确定变量的类型,在调用时,由开发者指定具体的类型。
1. 如何给arg参数和函数指定类型?
function identity(arg){return arg;
}identity(1)
identity('jack')
identity(true)
identity([])
identity(null)
定义的时候,无法确定类型,只有在调用的时候,才能确定参数类型。
function identity<T>(arg:T):T{return arg;
}identity<number>(1)
identity<string>('jack')
2. 多个类型如何传递?
function identity(x,y){return x;
}identity(1,2)
identity('a',2)function identity<T,U>(x:T,y:U):T{return x;
}
identity<number,number>(1,2)
identity<string,number>('a',2)
回顾一下任意属性
interface Person{[k:string]: string | number | boolean;
}
任意属性是不确定有什么属性,泛型是不确定有什么类型。
3. Pick的使用
Pick 就是挑选的意思,可以从已有的类型中,挑选一些类型进行使用。
interface User{id: number;name: string;age: number;
}type AgeType = Pick<User, 'age' | 'name'>let Jack:AgeType = {name: 'Jack',age: 30
}