简体   繁体   English

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

[英]Typescript ignores wrong return type when using outside type

The following snipped allows action to return a string:以下片段允许操作返回字符串:

type Action = () => { error?: any };

const action: Action = () => {
   if (Math.random()) {
        return {}
    };

    return "" // ?
}

But not the following:但不是以下内容:

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

    return "" // Error
}

Would love an explanation as this error has me desperate.希望得到一个解释,因为这个错误让我绝望。 Here is a playground .这里是一个游乐场

I think it's because of weak type detection .我认为这是因为弱类型检测 Typescript will not let you return any value which has no overlap with the return type of the function. Typescript 不会让您返回任何与 function 的返回类型不重叠的值。 To mitigate it you can do the following: return "" as {error?: any} or return "" as Action为了缓解它,您可以执行以下操作: return "" as {error?: any}return "" as Action

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM