Generics
the difference
1. Don't use generics
const returnStr = (str: string): string => {
return str;
};
const returnNumber = (num: number): number => {
return num;
};
2. Use Generics
const returnFun = <T>(varData: T): T => {
return varData;
};
console.log(returnFun<string>('123456'))
console.log(returnFun('liuqing'))//自动类型推论
The information we can learn from the above example:
1. Using generics can achieve reuse;
2. After using generics, the calling method can be written <xxx>
or not, ts will automatically type inference;
3.T is a variable, Can be any character variable.
Array Generics
We can also use the Array Generic Array to represent arrays:
let arr: Array<number> = [1,2,2,3];
Array<number>
===number[]
Refer to: typeScript foundation (6)_array type
Multiple type parameters
const returnFun = <T,G>(varData1: T,varData2:G): [T,G] => {
return [varData1,varData2]
};
console.log(returnFun<string,number>('123456',123456)) //['123456',123456]
The returnFun function passes in two different types of data and returns them as a tuple type.
type constraints
interface Tface {
length:number
}
const returnFun = <T extends Tface>(varData: T): T => {
return varData ;
};
console.log(returnFun<string>("123456"));
// console.log(returnFun<number>(123456)); //类型“number”不满足约束“Tface”
When T deteriorates that Tface several times, T is constrained. At this time, the parameters we pass in can only pass the value containing the length attribute.
generic interface
interface Tface {
<T>(zjq: T): T;
}
const myFun: Tface = <T>(aaa: T): T => {
return aaa;
};
console.log(myFun("六卿"))
generic class
class F<T> {
name: T;
add: (num1: T) => T;
}
let f: F<string> = new F<string>();
f.name = "liuqing";
f.add = (num1: string) => num1;
Using type parameters in generic constraints
You can declare a type parameter and it is constrained by another type parameter. for example
const myFun = <T extends G, G>(prop: T, obj: G): T => {
return prop;
};
let x = {
a: 1, b: 2, c: 3, d: 4 };
console.log(myFun(x, {
b: 10, d: 20 }));
The above means that the first parameter of the function myFun inherits the second parameter, so when the first parameter is passed in, the second parameter must be included. The range of T can only be wider than that of G.