Skip to content

Strange "Object is possibly 'null'" assumption #35964

Closed
@simonwep

Description

@simonwep

Code

I've got the following code:

interface MyGenerator {
    nextItem(): null | string;
    throwError(): never;
}

type GeneratorMapperFn = (gen: MyGenerator) => string | null;
const mapTokenFunction = (fn: GeneratorMapperFn) => {
    return (gen: MyGenerator): string | null => {
        return fn(gen);
    };
};

// The error occurs at this "function", TS seems to know that "gen" implements "MyGenerator"
// but tells me instead that "next" could be null at the very end.
const mappedFunction = mapTokenFunction(gen => {
    const next = gen.nextItem();

    if (!next) {
        gen.throwError();
    }

    // TS2531: Object is possibly 'null'
    return next.toUpperCase();
});

TS Playground

It gets even more strange, if I replace the gen.throwError() with a throw "Foo" it works:

TS Playground

... or if gen got an explicit type-assignment ((gen: )):

TS Playground

Although TS tells me that gen is of type MyGenerator:
F1AqNpfMgn

Expected behavior:
TS should correctly assume that next cannot be null after the conditional statement.

Actual behavior:
It throws TS2531: Object is possibly 'null'.

Related Issues:
#34795, #9998

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