【问题标题】:Typescript: incorrect type checking for function that returns void打字稿:对返回 void 的函数的类型检查不正确
【发布时间】:2020-07-08 09:28:57
【问题描述】:

谁能给我解释一下为什么我下面写的代码似乎不能区分以下两种类型:

[1] () => void(不带参数的函数类型不返回任何内容)

[2] () => () => void(一个不带参数的函数并返回一个不带参数且不返回任何内容的函数)。

例如:

const function2 = (): () => void => {
  return (): void => {};
};

export const function1 = (arg: () => void): void => {
  console.log(arg);
};

function1(function2); // Should NOT pass type checker as the return type is not void
function1(function2()); // Should pass type checker

或者,有人可以告诉我如何让function1(function2) 引发 Typescript 编译错误。

【问题讨论】:

标签: typescript typescript-typings


【解决方案1】:

函数function1 不处理arg 函数的结果(void 无法处理)。因此编译器允许函数返回一些东西。如果您将arg 设为返回一些可处理结果的函数,它也会在传递函数返回另一个具有正确返回类型的函数的情况下发出警告。

【讨论】:

    猜你喜欢
    • 2021-11-19
    • 2015-08-10
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多