【问题标题】:How to define Object Property as Function = Correct Syntax?如何将对象属性定义为函数 = 正确的语法?
【发布时间】:2020-02-11 21:50:19
【问题描述】:

有人可以指出规范的确切位置以了解testMessage: (): string => { 行的语法。语法不应该类似于testMessage: () => string;吗?为什么它们不同?

export default {
  Query: {
    testMessage: (): string => {
      return 'Hello World!';
    }
  }
};

【问题讨论】:

标签: typescript function types


【解决方案1】:

这有点令人困惑,因为您的: 在同一行中有两个不同的函数:第一个是来自 JavaScript 的字典赋值,第二个是来自 TypeScript 的类型信息。

let someMessageWithoutReturnType = () => { return 'Hello World!'; }
//                                 ^-- lambda function -----------^

let someMessage =                  (): string => { return 'Hello World!'; }
//                                   ^-type-^
//                                 ^-- lambda function -------------------^

在上述每一个中,变量都没有类型信息。相反,lambda 函数具有可选的类型信息——显式返回类型——如 standard function syntax in this example in the Functions page of the handbook

function add(x: number, y: number): number {
   return x + y;
}

let myAdd = function(x: number, y: number): number { return x + y; };

如果您在字典中赋值,此行为仍然相同,但第一个 : 代替了赋值中的 =,而第二个 : 将返回类型信息提供给函数表达式。这里是明确的,因为您不能使用冒号在字典中显式键入键 someMessage;你需要一个明确的演员表。

let someMessageDict = {
  someMessage: (): string => { return 'Hello World!'; }
//             ^-- lambda function -------------------^
};

相比之下,您提到的语法是用于键入变量,如"Writing the function type" 部分所述。请注意,这一次,变量是显式类型的,但没有设置为任何值;没有实现它。

let testMessage: () => string;

class SomeClass {
  testMessage:  () => string;  // defines an unset field
  testMessage2: () => string = SOME_FUNCTION_DECLARED_ELSEWHERE;
  testMessage3: () => string = (): string => { /* ... */ };
}

类定义说明了这可能令人困惑的地方:: 指的是类型信息,= 将设置一个初始值。也就是说,同样的逻辑适用:使用=> 描述类型表达式中的返回类型,使用: 使用返回类型注释内联函数定义(可能使用=> 语法本身)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 2021-09-20
    相关资源
    最近更新 更多