Closed
Description
TypeScript Version: 2.9.2
Search Terms: typeof undefined guard property strictnullchecks
Code
With --strictNullChecks
:
const obj: { [key: string]: string | undefined } = {}
const withAssignment = (key: string): string | null => {
const value = obj[key];
return typeof value === 'undefined'
? null
: value;
}
const withTernary = (key: string): string | null =>
return typeof obj[key] === 'undefined'
? null
: obj[key];
// Type 'string | null | undefined' is not assignable to type 'string | null'.
// Type 'undefined' is not assignable to type 'string | null'.
const withIf = (key: string): string | null => {
if (typeof obj[key] === 'undefined') {
return null;
} else {
return obj[key];
// Type 'string | undefined' is not assignable to type 'string | null'.
// Type 'undefined' is not assignable to type 'string | null'.
}
}
Expected behavior:
- Just like the example in the docs but with an
undefined
instead of astring
. - No error.
- No additional explicit check.
- The property does not change in this simple statement so the type assertion should be OK.
Playground Link:
http://www.typescriptlang.org/play/#src=...
Related Issues: