Closed
Description
TypeScript Version: 3.5.1
Search Terms:
Indexed, Partial, undefined, guard
Code
function getValue<T, K extends keyof T>(partial: Partial<T>, key: K): T[K] | null {
const value = partial[key]
if (value !== undefined) {
return value // error: TypeScript thinks this can be undefined...
}
return null
}
Expected behavior:
Inside the if statement, value
should have type T[K]
. Especially since partial[key]
is assignable to T[K] | undefined
, and in fact TypeScript reports the type in the error message as T[K] | undefined
, inside the if statement! It's like it just doesn't simplify Partial<T>[K]
until it tries returning it.
Here is the workaround, which doesn't involve any casting, just hints:
function getValue<T, K extends keyof T>(partial: Partial<T>, key: K): T[K] | null {
const value: T[K] | undefined = partial[key]
if (value !== undefined) {
return value // OK
}
return null
}
It would be nice if this hint wasn't necessary.
Actual behavior:
TypeScript complains that T[K] | undefined
is not ok to return, even though the type should be T[K]
.
Playground Link:
(requires strictNullChecks)
Related Issues: