Using optional chaining and array.length invalidates typescript narrowing

Viewed 964

I just noticed that typescript doesn't know that an variable is not null if I use the length property while narrowing the type:

declare const foo: { method: () => void, groups: number[] } | undefined;

if (foo?.groups.length > 0) {
    foo.method();
}

That gives you an error saying that object is possibly undefined. If you remove the length check, then it works as expected. Is this a TS limitation? expected behaviour? bad practice?

playground link

0 Answers
Related