【问题标题】:Anonymous function signature in typescript type. What does this mean?打字稿类型中的匿名函数签名。这是什么意思?
【发布时间】:2020-02-11 20:52:03
【问题描述】:

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


    【解决方案1】:

    这是另一种写法:

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

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

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

    ...为一个函数定义一个类型,该函数接受一个字符串,返回一个数字,并有一个 b 属性(在函数上),它是一个布尔值。

    Fun on the playground:

    // 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
    

    【讨论】:

    • 我通常会引用文档,但是...我在文档中找不到它。 :-) 我在操场上玩弄明白了。
    • 感谢您的回答,但现在我有一个后续问题:在这样的类型中也可以有多个匿名函数签名: type Foo = { (a: string): number, ( a: number): string } 那么这是某种重载吗?
    • @ManuelMauky - Looks that way,是的。 :-)
    • 这真的很有趣。但它仅在返回类型相同时才有效。如果返回类型不同,它将停止工作:Link
    • @ManuelMauky - 这很有趣......你可以通过正常的函数重载来做到这一点。呵呵。
    猜你喜欢
    • 2020-01-01
    • 2018-02-06
    • 2020-02-13
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    相关资源
    最近更新 更多