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
未经授权禁止转载,违者必究!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
2021-04-15 Linux scp command All In One
2021-04-15 import { componentName as componentAlias} form module
2021-04-15 how to install Nginx on CentOS 7 All In One
2021-04-15 how to upload files to CentOS 7 on macOS by using zsh
2021-04-15 Mobile App Store Marketing Intelligence All In One
2021-04-15 App 免费托管分发平台 All In One
2020-04-15 软件考试 2020