TypeScript 入门学习(三):TypeScript 函数定义

叁歲伎倆 2021-09-30 06:42 587阅读 0赞

TypeScript 函数定义

函数定义

  1. // 函数声明法
  2. function fun(): string { return 'xxx';}
  3. // 匿名函数声明法
  4. var fun = function(): string { return 'xxx';}

函数传参

  1. // 传入参数
  2. function foo(name: string, age: number): string {
  3. return `${name}---${age}`;
  4. }
  5. console.log(getInfo('star', 23)); // star---23

可选参数

  1. function foo(bar: number, bas?: string): void {
  2. if (bas) {
  3. console.log(`${bar}---${bas}`);
  4. } else {
  5. console.log(bar);
  6. }
  7. }
  8. foo(123); // 123
  9. foo(123, 'hello'); // 123---hello

注意: 可选参数必须放在必选参数的后面。

  1. // 错误写法
  2. function foo(bar: number, bas?: string, co: string): void {
  3. // ...
  4. }

默认参数

当调用者没有提供该参数时,你可以提供一个默认值(在参数声明后使用 = someValue )。

  1. function foo(bar: number, bas: string = 'hello'): void {
  2. console.log(bar, bas);
  3. }
  4. foo(123); // 123 hello
  5. foo(123, 'world'); // 123 world

Rest 参数

  1. function foo(bar: string, ...arg: number[]): void {
  2. console.log(bar);
  3. for (const e of arg) {
  4. console.log(e);
  5. }
  6. }
  7. foo('hello', 1, 3, 4, 5); // hello 1 3 4 5

注意: Rest 参数必须放在必选参数后面,并且可选参数和 Rest 参数是兼容的。

函数重载

TypeScript 中的重载是通过同一个函数提供多个函数类型定义来实现多种功能的目的。

  1. function foo(name: string): void;
  2. function foo(name: string, age: number): void;
  3. function foo(name: string, age?: number): void {
  4. if (age) {
  5. console.log(`${name}---${age}`);
  6. } else {
  7. console.log(name);
  8. }
  9. }
  10. foo('star');foo('star', 23);

最后一个函数头是在函数体内实际处于活动状态但不可用于外部。TypeScript 中的函数重载没有任何运行时开销。它只允许你记录希望调用函数的方式,并且编译器会检查其余代码。

发表评论

表情:
评论列表 (有 0 条评论,587人围观)

还没有评论,来说两句吧...

相关阅读