Closed
Description
I'm getting some wierd behavior when trying to match possibly undefined type of a value from a mapped type with a generic union including undefined
. strictNullChecks
flag is on.
The code below better describes the problem.
TypeScript Version: 2.4.1
Code
// A *self-contained* demonstration of the problem follows...
type TStorage = {
a?: number,
b?: string
};
const storage: TStorage = {
a: 1,
b: '2'
};
//this was original function signature with return type
//but was commented to better reflect the problem with type inference
//function get<K extends keyof TStorage>(key: K): TStorage[K] {
function get<K extends keyof TStorage>(key: K) {
//inferred type of result
// const result: {
// a?: number | undefined,
// b?: number | undefined
// }[K]
const result = storage[key];
return fromUndefined(storage[key]);
}
function fromUndefined<T>(value: T | undefined): T {
return value!; //cast here is just for example
}
declare const b: string | undefined;
//const bb: string - correct
const bb = fromUndefined(b);
//const value: number | undefined - correct
const value = storage.a;
//const value2: number - also correct
const value2 = fromUndefined(storage.a);
//const a: string | undefined <---- Why undefined?
const a = get('b');
Expected behavior:
last const a
is of type string
Actual behavior:
last const a
is of type string | undefined
Is it correct behavior and I'm missing something about mapped types?
Metadata
Metadata
Assignees
Labels
No labels