Skip to content

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

Closed
@Septh

Description

@Septh

πŸ”Ž 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

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