Skip to main content

TypeScript 类型定义小技巧

· 2 min read
Alan

TypeScript定义小技巧

函数重载

引用文档

makeDate.ts
export function makeDate(timestamp: number): Date;
export function makeDate(m: number, d: number, y: number): Date;
export function makeDate(mOrTimestamp: number, d?: number, y?: number): Date {
if (d !== undefined && y !== undefined) {
return new Date(y, mOrTimestamp, d);
} else {
return new Date(mOrTimestamp);
}
}
const d1 = makeDate(12345678);
const d2 = makeDate(5, 5, 5);
const d3 = makeDate(1, 3);
note
  1. 如果需要导出(export)函数, 那每个函数定义都要导出(export)
  2. 实际代码实现要写在参数最多那个重载定义里

也可以借助interface或者type实现:

makeDate.ts
interface MakeDateDef {
(val: string): Date
(year: number, month: number): Date
}

export const makeDate: MakeDateDef = function(valOrYear: string | number, month?: number) {
/**
* 具体函数实现
*/
}

函数属性/字段定义

使用 type 定义

loadJs.ts
type LoadJsDef = {
(src: string): Promise<string>
__caches: { [key: string]: Promise<string> }
}
export const loadJs: LoadJsDef = function (src: string) {
/** 函数实现*/
loadJs.__caches["url"] = Promise.resolve("values");
};
loadJs.__caches = { };

或者使用 interface:

loadJs.ts
interface LoadJsDef {
(src: string): Promise<string>
__caches: { [key: string]: Promise<string> }
}
export const loadJs: LoadJsDef = function (src: string) {
/** 函数实现*/
loadJs.__caches["url"] = Promise.resolve("values");
};
loadJs.__caches = { };