TypeScript类型中的匿名函数签名是什么意思?这代表什么?

3

我知道如何在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
}

所以问题是:上面的类型定义实际上意味着什么?是否可能创建与该签名匹配的对象?
1个回答

5

这是一种另类的写法:

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

我通常会引用文档,但是......我在文档中找不到它。 :-) 我通过在游乐场上玩耍来解决它。 - T.J. Crowder
谢谢你的回答,但是我现在有一个跟进的问题:像这样,在类型中有多个匿名函数签名也是可能的:type Foo = { (a: string): number, (a: number): string }那么这是种重载吗? - Manuel Mauky
@ManuelMauky - 看起来是这样,是的。 :-) - T.J. Crowder
1
这真的很有趣。但它只在返回类型相同时起作用。如果返回类型不同,它就停止工作:链接 - Manuel Mauky
@ManuelMauky - 这很有趣...你可以使用普通函数重载来实现。哦。 - T.J. Crowder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接