Typescript在使用外部类型时忽略错误的返回类型



下面的代码允许操作返回一个字符串:

type Action = () => { error?: any };
const action: Action = () => {
if (Math.random()) {
return {}
};
return "" // ?
}

但不包括以下内容:

const action = (): { error?: any } => {
if (Math.random()) {
return {}
};
return "" // Error
}

希望有一个解释,因为这个错误已经让我绝望了。这是一个操场。

我认为这是因为弱类型检测。Typescript不会让你返回任何与函数的返回类型没有重叠的值。要减轻它,您可以执行以下操作:return "" as {error?: any}return "" as Action

相关内容

最新更新