Skip to content

Inconsistent behavior of the never return type between function and class method #61464

Description

🔎 Search Terms

never return type

🕗 Version & Regression Information

  • This is the behavior in every version I tried

⏯ Playground Link

https://www.typescriptlang.org/play/?target=99&moduleResolution=99&esModuleInterop=false&strictBuiltinIteratorReturn=false&useUnknownInCatchVariables=false&alwaysStrict=false&noImplicitOverride=true&noPropertyAccessFromIndexSignature=true&suppressImplicitAnyIndexErrors=false&suppressExcessPropertyErrors=false&allowUnreachableCode=true&declaration=false&jsx=0#code/JYOwLgpgTgZghgYwgAgCoAtQHNkG9kAOUA9gQFzIDOYU2yAvgFAAmECANnFCjAK4gIwwYiGRYIYAMrEAthMwgsACgCUFDHQA+yEL3btGjAPRHkAQWR8BQkcjDo4YHRABu0ZNzC8oISoyuCwqLwwOyqFCCu7riMyHF26CQA7s4pAKJQJFBKAOTEpJQ5KoxMjAgi1AnYAIzIALxiEtJy9tiqjMAwyEoAhK2K1cXxlnCh7f1Y1QB0RKTxJsgAPAC0y1UDyMCUaAo4gKDkhgsWHHCU20nA9shwyC3oxMwJjs5uUB4S3r5lnGfIaQAel2isXiITCahewOGw3syVSf0yxGyeQKRRBcSYpXKvic-xo9XhAKB2WK2MqEwATATxFJZPI2sVOt0+rsKUN4nioFMweNWTMSAR5qYVmtKZtthpFMhtLp9MhADLkhmMpgAQrwnPYUHAAEbENzIJJIgDW53QEFEmuQxG1ACs2E4toRTpQII9TtcnVA4C13IA+DcAKLv+fiBWwwEBKCCAyBQChE6MqPDo5BkjW7ADM1KadIm7WGTN6EzT7OhyEjxO5o3BScL-LmcQWIvWWAzjsl+xKjCAA

💻 Code

interface Thing { prop: any }
declare function getSomething(): Thing | null

// A function that never returns
function fail(): never {
    throw new Error('oops')
}

const thing1 = getSomething()
if (!thing1)
    fail()
thing1.prop   // <-- ✅ thing1 is Thing

// A class with a method that never returns
class Exiter {
    fail(): never {
        throw new Error('oops')
    }
}

const xtr = new Exiter()
const thing2 = getSomething()
if (!thing2)
    xtr.fail()
thing2.prop   // <-- ❌ thing2 is Thing | null (ts18047)


// But the above works when the Exiter instance is passed as a parameter 🤔
function fn(exiter: Exiter) {
    const thing3 = getSomething()
    if (!thing3)
        exiter.fail()
    thing3.prop   // <-- ✅ thing3 is Thing
}

🙁 Actual behavior

'thing2' is possibly 'null'. (ts18047) on case 2.

🙂 Expected behavior

Should compile.

Additional information about the issue

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions