首页 > 解决方案 > 打字稿类型中的匿名函数签名。这是什么意思?

问题描述

我知道如何在 TypeScript 中定义一个需要这样的命名函数的类型:

type Foo = {
    bar(a: string): number
}

// or

type Foo = {
    bar: (a:string) => number
}

然而,使用第一种方法,也可以定义一个没有名字的函数,如下所示:

type Foo = {
    (a: string): number
}

TypeScript 编译器在这里没有抱怨,但我不知道如何创建与此类型签名匹配的对象?尝试这样的事情不会编译:

let f: Foo = {
  (a: string) => 2
}

所以问题是:上面的类型定义实际上是什么意思?是否可以创建与此签名匹配的对象?

标签: typescript

解决方案


这是另一种写法:

type Foo = (a: string) => number;

...但您也可以包含该函数将具有的其他属性,例如:

type Foo = {
    (a: string): number;
    b: boolean;
};

...为接受字符串、返回数字并具有b布尔属性(在函数上)的函数定义类型。

操场上的乐趣

// Your type
type Foo = {
  (a: string): number;
};

// Equivalent type
type Bar = (a: string) => number;

// Proving they're equivalent (or at least compatible)
const a: Foo = (a: string) => 42;
const b: Bar = a; // <== Works

// Including a property on the function
type Foo2 = {
  (a: string): number;
  b: boolean;
};

// Creating one
const x1 = (a: string): number => 42;
let f1: Foo2 = x1; // <== Error because `x1` doesn't have `b`

const x2 = (a: string): number => 42;
x2.b = true;
let f2: Foo2 = x2; // <== Works

推荐阅读