Support preserving type narrowing inside closures in some simple cases ยท Issue #55528 ยท microsoft/TypeScript (original) (raw)

๐Ÿ” Search Terms

โœ… Viability Checklist

โญ Suggestion

I understand that types are not kept narrowed inside callbacks because the narrowing could in general not hold anymore in there, however there are some "simple" scenarios where we can be sure that the narrowing holds, for example:

function foo () {

let maybe: string | null;

maybe = 'foo';

console.log ( () => {

maybe;
// ^?

});

}

This scenario is a sort of a simple edge case of the general problem because:

Under these conditions it's impossible for narrowing the type inside our function in the example above to be wrong, so it should be preserved.

๐Ÿ“ƒ Motivating Example

Playground: https://www.typescriptlang.org/play?#code/FAMwrgdgxgLglgewgAhAhyAUBKZBvYYZZAGwFMZkBbAQwE8AjMgLmQGcYAnOCAc2QA+yCGBIkA3IWK1GZZAF5kAcjQIlkosihI2CcgDoSCfpiy55APnxTi1ek0m3kAemfIAegH4bAX2zjiQh9gIA

๐Ÿ’ป Use Cases

Preserving narrowing in simple cases like the one mentioned above is very handy and allows the user to write clean code in more scenarios.