简体   繁体   中英

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. To mitigate it you can do the following: return "" as {error?: any} or return "" as Action

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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