TypeScript Version: typescript@3.6.0-dev.20190809
Search Terms: unknown, type guard, double-equals, ==, null
Code
Minimal repro case:
export function test(v: unknown) {
let nullOrUndefined: null | undefined;
if (v === null || v === undefined) {
// This works, as `v` is narrowed to `null | undefined`.
nullOrUndefined = v;
}
if (v == null) {
// Error: Type 'unknown' is not assignable to type 'null | undefined'.
nullOrUndefined = v;
}
}
A more practical use-case for the narrowing would be something like this:
if (typeof v === 'string' || v == null) {
// v should be `string | null | undefined` in here.
if (v) {
// v is a non-empty string
doSearch(v);
} else {
// v is empty string, null, or undefined
clearSearch();
}
}
Expected behavior:
v == null narrows an unknown type to null | undefined, same as v === null || v === undefined does.
Reading the ECMAScript spec on ==, I believe that == null will guarantee that the value is either null or undefined. == undefined would do the same thing, though linters generally prefer the shorter == null.
Actual behavior:
Compile error:
src/index.ts:11:5 - error TS2322: Type 'unknown' is not assignable to type 'null | undefined'.
Type 'unknown' is not assignable to type 'null'.
11 nullOrUndefined = v;
~~~~~~~~~~~~~~~
Found 1 error.
Playground Link: https://www.typescriptlang.org/play/#code/KYDwDg9gTgLgBAMwK4DsDGMCWEVxsAZxgAoA3ALjlQGsUIB3FASjgG8AoOOAG2HhSTduAeSgBVFABNgCTCmCTKAoXAA+VKTLkKA3JziYEcMnAC85uMu5r1pMxdTTZ8ySw5cuAek9wAKgAtMAjh6aGoCADp9LitRCSdtSTM4Uj0uAF99Q2M7Cys3aLhvPwBPMGA4AHIaOkZKg2C6eABDAgJMAHMUZoAjXjwIPDKKyqs1DQSXSqiPS0ERcU1nBWTU-UzMoA
Related Issues:
TypeScript Version: typescript@3.6.0-dev.20190809
Search Terms: unknown, type guard, double-equals, ==, null
Code
Minimal repro case:
A more practical use-case for the narrowing would be something like this:
Expected behavior:
v == nullnarrows anunknowntype tonull | undefined, same asv === null || v === undefineddoes.Reading the ECMAScript spec on
==, I believe that== nullwill guarantee that the value is either null or undefined.== undefinedwould do the same thing, though linters generally prefer the shorter== null.Actual behavior:
Compile error:
Playground Link: https://www.typescriptlang.org/play/#code/KYDwDg9gTgLgBAMwK4DsDGMCWEVxsAZxgAoA3ALjlQGsUIB3FASjgG8AoOOAG2HhSTduAeSgBVFABNgCTCmCTKAoXAA+VKTLkKA3JziYEcMnAC85uMu5r1pMxdTTZ8ySw5cuAek9wAKgAtMAjh6aGoCADp9LitRCSdtSTM4Uj0uAF99Q2M7Cys3aLhvPwBPMGA4AHIaOkZKg2C6eABDAgJMAHMUZoAjXjwIPDKKyqs1DQSXSqiPS0ERcU1nBWTU-UzMoA
Related Issues:
unknownwas added in Fix #25172: Add narrowing forunknownwith triple equals #26941== nullis well-defined and can be special-cased.unknown#25720 open for better narrowing ofunknown.