TypeScript generic All In One
TypeScript generic All In One
function generic
// arrow function :
// : <T>(name: T) => T 类型定义
// = <T>(name: T) => {} 函数定义
const ArrowFunc: <T>(name: T) => T = <T>(name: T) => {
return name;
}
// 简写 arrow function =
const ArrowFunc1 = <T>(name: T) => {
return name;
}
// const sum = <T>(a: T, b: T): any => {
// return `a = ${a}, b = ${b}`;
// }
// 单个泛型参数 T
const sum = <T>(a: T, b: T) => {
return `a = ${a}, b = ${b}`;
}
// 类型推断
sum(1, 2);
sum('1', '2');
sum<number>(1, 2);
sum<string>('1', '2');
// 多个泛型参数
const multiGeneric = <T, P>(a: T, b: P) => {
return `a = ${a}, b = ${b}`;
}
// 类型推断
multiGeneric(1, 2);
multiGeneric('1', 2);
multiGeneric('1', '2');
multiGeneric<number, number>(1, 2);
multiGeneric<string, number>('1', 2);
multiGeneric<string, string>('1', '2');
class generic
class ArrayData<T>{
constructor(private arr: T[]) {
//
}
getItem: (index: number) => T = (index: number) => {
return this.arr[index];
}
}
const numArr = new ArrayData([1, 2, 3]);
numArr.getItem(1);
const strArr = new ArrayData(['a', 'b', 'c']);
strArr.getItem(1);
type ObjType = {
name: string;
};
class ArrayDataObj<T>{
constructor(private arr: T[]) {
//
}
getItem(index: number): T {
return this.arr[index];
}
getItemName(obj: ObjType): string {
return obj.name;
}
}
// 没有类型限制 T 可以是任何类型
const objs = new ArrayDataObj<ObjType>([
{
name: 'abc',
},
{
name: 'xyz',
// name: 123,
}
]);
objs.getItem(1);
// 类型限制 extends, T 只能是限制的指定类型
type LimitTypes = (string | number);
class ArrayData1<T extends LimitTypes>{
constructor(private arr: T[]) {
//
}
getItem(index: number): T {
return this.arr[index];
}
}
const arr1 = new ArrayData1([1, 2, 3]);
arr1.getItem(1);
// 有类型限制, T 只能是限制的指定类型
const objs1 = new ArrayData1<ObjType>([
{
name: 'abc',
},
]);
objs1.getItem(1);
// Type 'ObjType' does not satisfy the constraint 'LimitTypes'.ts(2344)
demo
refs
https://www.typescriptlang.org/docs/handbook/generics.html
https://www.typescriptlang.org/docs/handbook/2/generics.html
https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html#generics
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16147215.html
未经授权禁止转载,违者必究!