TypeScript学习六:function

89 阅读1分钟

定义一个函数

let fnAdd: (x: number, y: number) => number;
fnAdd = (arg1: number, arg2: number): number => arg1 + arg2;

type: 使用别名定义函数

type fnAdd2 = (arg1: number, arg2: number) => number;
let fn2: fnAdd2 = (arg1: number, arg2: number): number => arg1 + arg2;

可选参数"?"

type fnAdd3 = (arg1: number, arg2?: number) => number;
let fn3: fnAdd3 = (arg1: number, arg2?: number) => arg1 + (arg2 || 0);

默认参数

let fnAdd4 = (arg1 = 3, arg2: number) => arg1 + arg2;
fnAdd4("a", 5); // err: 会根据默认值推倒类型 number | undefined

函数重载

根据传入的值或类型不一样返回不一样的结果

function fn5(arg: string): string[];
function fn5(arg: number): number[];
function fn5(arg: any): any {
  if (typeof arg === "string") {
    return arg.split("");
  } else {
    return arg
      .toString()
      .split("")
      .map((item: number) => Number(item));
  }
}
// fn5("123").map(item => item.toFixed())   // err: 属性“toFixed”在类型“string”上不存在
console.log(fn5("123"));
console.log(fn5(123));