一.指定函数参数类型
const getArray = <T>(times:number,val:T):T[]=>{
let result:T[] = [];
for(let i = 0; i<times;i++){
result.push(val);
}
return result;
}
console.log(getArray<number>(3,3)); // 3 => T => number
function swap<T, K>(tuple: [T, K]): [K, T] {
return [tuple[1], tuple[0]]
}
console.log(swap(['a','b']))
二.函数标注的方式
type TArray = <T, K>(tuple: [T, K]) => [K, T];
const getArray:TArray = <T, K>(tuple: [T, K]): [K, T] => {
return [tuple[1], tuple[0]]
}
interface IArray{
<T,K>(typle:[T,K]):[K,T]
}
const getArray:IArray = <T, K>(tuple: [T, K]): [K, T] => {
return [tuple[1], tuple[0]]
}
三.泛型接口使用
interface ISum<T> { // 这里的T是使用接口的时候传入
<U>(a: T, b: T): U // 这里的U是调用函数的时候传入
}
let sum: ISum<number> = (a:number, b:number) => {
return 3 as any
}
四.默认泛型
interface T2<T=string>{
name:T
}
type T22 = T2;
let name1:T22 = {name:'james'}
type T23 = T2<number>;
let name1:T23 = {name:'james'}
// (property) T2<number>.name: number
// Type 'string' is not assignable to type 'number'.ts(2322)
// 1.ts(19, 5): The expected type comes from property 'name' which is declared here on type 'T22'
五.类中的泛型
class MyArray<T>{ // T => number
arr: T[] = [];
add(num: T) {
this.arr.push(num);
}
getMaxNum(): T {
let arr = this.arr
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
let current = arr[i];
current > max ? max = current : null
}
return max;
}
}
let myArr = new MyArray<number>();
myArr.add(3);
myArr.add(1);
myArr.add(2);
console.log(myArr.getMaxNum());
const createClass = <T>(clazz: new(name:string,age:number)=>T):T =>{
return new clazz(name,age);
}
createClass<Person2>(Person2)
六.泛型约束
interface IWithLength {
length:number
}
function getLen<T extends IWithLength>(val:T){
return val.length;
}
getLen('hello');
const sum = <T extends number>(a: T, b: T): T => {
return (a + b) as T
}
let r = sum<number>(1, 2);
const person = {
name: "james",
age: 18
};
const getVal = <T,K extends keyof T>(obj:T,key:K) : T[K]=>{
return obj[key];
}
console.log(getVal(person, "name")); // james
console.log(getVal(person, "name1"));
// Argument of type '"name1"' is not assignable to parameter of type '"name" | "age"'.ts(2345)
发表评论
还没有评论,快来抢沙发吧!