Skip to content

nullable object type does not narrow with a "never" functionΒ #52784

Closed
@ArcticZeroo

Description

@ArcticZeroo

Bug Report

πŸ”Ž Search Terms

some variations/permutations of "narrow never null"

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about type narrowing/never functions

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

const throwError = (): never => { throw new Error(); };
const someFunc = (): string | undefined => "hello world";

const getA = (): string => {
    const a = someFunc();

    if (!a) {
        throwError();
    }

    return a;
}

πŸ™ Actual behavior

Compilation fails because TS thinks that a may be null when returning it from getA.

πŸ™‚ Expected behavior

Because throwError is never, TS should be able to see that I will never reach the return statement if a is null (or falsy at all). Even if I explicitly check for if (a == null), control flow analysis does not seem to narrow the type here.

So, expected behavior is that compilation succeeds and the type is narrowed to just string.

I see this related issue which implies that I should be able to narrow my type by calling a never function: #50739 , but I cannot reproduce the behavior of narrowing a.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions