首页 > 解决方案 > 为什么 Typescript 让我在一个应该返回 void 的函数中返回一个非 void 值

问题描述

我有这个类声明:

class Event {
    action: () => void;

    constructor(identifier: string, action: () => void) {
        (...)
    }
}

然后,Typescript 让我从该类构造一个带有action参数函数的对象,该函数不会返回 void 而不会出错,例如:

const newObject = new Event("string", () => {
    return "string";
});

但是,如果我将参数函数的返回类型更改actionstring例如在类声明中,然后构造一个其参数action返回数字的对象,它确实会显示预期的错误:

Argument of type '() => number' is not assignable to parameter of type '() => string'.
Type 'number' is not assignable to type 'string'.

标签: typescript

解决方案


推荐阅读