自学内容网 自学内容网

TypeScript06:函数的相关约束

函数重载:在函数实现之前,对函数调用的多种情况进行声明。

// 函数重载
function combine(a: number, b: number):number
function combine(a: string, b: string):string
function combine(a: number | string, b: number | string): number | string { 
  if (typeof a === "number" && typeof b === "number") {
    return a * b
  } else if (typeof a === "string" && typeof b === "string") { 
    return a + b
  }
  throw new Error("a和b必须是相同时类型")
}
const result1 = combine(1, 2);
const result2 = combine("hello", "world");
console.log(result1,result2); // 2 helloworld

可选参数:可以在某些参数名后加上问号,表示该参数可以不用传递。不传递时默认为undefined类型。可选参数必须在参数的末尾位置。

// 可选参数
function sayHello(name: string, age?: number) { 
  console.log(`hello ${name}, age is ${age}`);
}
sayHello("Rata") // "hello Rata, age is undefined"

为参数指定默认值:

// 指定默认值
function sayHello(name: string, age: number = 25) { 
  console.log(`hello ${name}, age is ${age}`);
}
sayHello("Rata") // hello Rata, age is 25


原文地址:https://blog.csdn.net/m0_60189088/article/details/136348827

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!