Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
simonwep opened this issue Jan 2, 2020 · 1 comment
Closed

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

simonwep opened this issue Jan 2, 2020 · 1 comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@simonwep
Copy link

simonwep commented Jan 2, 2020

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

@simonwep simonwep changed the title Strange "Object is possibly 'null'" message Strange "Object is possibly 'null'" assumption Jan 2, 2020
@ilogico
Copy link

ilogico commented Jan 2, 2020

I think this is a current limitation.
I don't know where the documentation for this is, but TS needs explicit type annotations for the assert and never returning functions to contribute to control flow analysis.
For now, you can fix this error by annotating (gen: MyGenerator) => ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

3 participants