TypeScript 允许我们声明函数重载。这对于文档 + 类型安全来说很实用:
export interface ResourceData {
id: string;
name: string;
data: any;
}
export function getResource(path: string): ResourceData;
export function getResource(path: string[]): ResourceData[];
export function getResource(path: string | string[]): any {
return {} as any;
}
const resource = getResource("a.json");// ResourceData
const resources = getResource(["b.json", "c.json"]); // ResourceData[]
不仅如此,函数重载也可以和范型结合起来,来实现更加强大的功能:
function compose<Input, FirstArg>(
func: (input: Input) => FirstArg
): (input: Input) => FirstArg
function compose<Input, FirstArg, SecondArg>(
func: (input: Input) => FirstArg,
func2: (input: Input) => SecondArg
): (input: Input) => SecondArg
function compose<Input, FirstArg, SecondArg, ThirdArg>(
func: (input: Input) => FirstArg,
func2: (input: Input) => SecondArg,
func3: (input: SecondArg) => ThirdArg
): (input: Input) => ThirdArg
function compose(...args: any[]){
return {} as any
}
const addOne = (a: number) => {
return a + 1;
}
const numToString = (a: number) => {
return a.toString();
}
const stringToNum = (a: string) => {
return parseInt(a);
}
const addOneToString = compose(addOne, numToString, stringToNum)