关于typescript:TypeScript-定义函数的几种写法

5次阅读

共计 2342 个字符,预计需要花费 6 分钟才能阅读完成。

  • 参考链接 1
  • 参考链接 2

写法 1 – 应用 function 关键字

function greeter(fn: (a: string) => void) {fn("Hello, World");
}

function printToConsole(s: string) {console.log(s);
}

greeter(printToConsole);

(a: string) => void

上述语法的含意:示意一个函数,接管一个字符串作为输出参数,没有返回参数。

能够应用 type 关键字定义一个别名:

type GreetFunction = (a: string) => void;

Call signatures

应用 call signatures 给函数减少额定的属性。TypeScript 的 function 也是 value,和其余 value 一样。

留神:肯定有 type 关键字。

源代码:

type DescribableFunction = {
    description: string;
    (someArg: number): boolean;
  };
  
function doSomething(fn: DescribableFunction) {console.log(fn.description + "returned" + fn(6));
}

const fn = (a: number) => a > 10;

fn.description = 'Jerry';

另一种定义形式:

type DescribableFunction = {
    description: string;
    (someArg: number): boolean;
  };
const fn = <DescribableFunction>({description: 'Jerry'});

const fn23 = Object.assign(function (number:number) {return number > 1},
  fn
);
function doSomething(fn: DescribableFunction) {console.log(fn.description + "returned" + fn(6));
}

Construct signatures

type SomeConstructor = {new (s: string): SomeObject;
};
function fn(ctor: SomeConstructor) {return new ctor("hello");
}

Method Signatures

办法签名语法可能是最容易应用的。在定义对象类型时,能够通过提供如下签名来轻松形容其办法:

interface Date {toString(): string;
  setTime(time: number): number;
  // ...
}

看个例子:

通过这种形式定义进去的函数,理论是一个 object:

如何实例化这种类型的 object?

const myDate = <MyDate>({toString: () => 'Jerry',
  setTime: (number) => number + 1
});

Function Type Literals

Function Type Literals 是另一种申明函数类型的办法。它们通常用于高阶函数的签名,即承受函数作为参数或返回函数的函数:

interface Array<T> {sort(compareFn?: (a: T, b: T) => number): this;
  // ...
}

兴许令人诧异的是,在函数类型文字中总是须要参数名称。您不能省略参数名称而只指定类型。

如果遗记指定形参名称,咱们将无奈失去冀望的类型定义。上面的代码是一个例子:

咱们本意想定义一个领有两个输出参数,一个返回参数的函数类型,输出参数类型别离为 string 和 number.

type FunctionType2 = (string, number) => number;
// (string: any, number: any) => number

实际上,TypeScript 编译器将 string 和 number 了解成了形式参数名,且类型为 any. 这就和咱们的冀望不统一了。

总结一下:

Object Type Literals with Call or Construct Signatures

在 JavaScript 中,函数只不过是能够调用的非凡对象。这个事实反映在对象类型文字的语法中:它们形容了对象的形态,它也恰好有一个调用签名:

interface RegExpConstructor {
  // Call signatures
  (pattern: RegExp): RegExp;
  (pattern: string, flags?: string): RegExp;

  // ...
}

与调用签名相似,对象类型文字也能够蕴含结构签名,在这种状况下,它被称为构造函数类型。当应用 new 运算符调用函数时,函数的结构签名 定义了它的参数列表和返回类型。结构签名 看起来与 调用签名 简直雷同,除了它们额定带有 new 关键字前缀:

interface RegExpConstructor {
  // Call signatures
  (pattern: RegExp): RegExp;
  (pattern: string, flags?: string): RegExp;

  // Construct signatures
  new (pattern: RegExp): RegExp;
  new (pattern: string, flags?: string): RegExp;

  // ...
}
// Using the call signature
const digitsPattern1 = RegExp("^\\d+$");

// Using the construct signature
const digitsPattern2 = new RegExp("^\\d+$");

更多 Jerry 的原创文章,尽在:” 汪子熙 ”:

正文完
 0