-
Notifications
You must be signed in to change notification settings - Fork 12.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Unable to infer type from union with undefined when using mapped types #16943
Comments
Optional parameter is marked as type TStorage = {
a?: number,
b?: string
};
type A = TStorage['a'] //=> number | undefined
type B = TStorage['b'] //=> string | undefined
type TStorageValue = TStorage[keyof TStorage] //=> string | number | undefined The following codes are considered equivalent on type-level, since their return types are specified declare function get<K extends keyof TStorage>(key: K): TStorage[K]; function get<K extends keyof TStorage>(key: K): TStorage[K] {
const result = storage[key];
return fromUndefined(storage[key]);
} |
I see. function get<K extends keyof TStorage>(key: K) /* No return type */ {
const result = storage[key];
return fromUndefined(storage[key]);
} Looks like UPDATE: |
Seems like // const result: {
// a?: number | undefined,
// b?: number | undefined
// }[K] is not evaluated when passing to That's why I'll try to rephrase the question - are there any plans to support such functionality or it's an intentional design decision? |
I have also updated original code with commenting |
fromUndefined(undefined); //=> expected never, but got undefined
function something<K extends keyof TStorage>(key: K) {
const result = storage[key]; //=> TStorage[K]
fromUndefined(storage[key]); //=> TStorage[K]
} For those real type subtraction, see #4183. |
Thanks for the anwser. #4183 contains lots of useful links to similar issues so I'm going to close this. |
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
Expected behavior:
last
const a
is of type stringActual behavior:
last
const a
is of typestring | undefined
Is it correct behavior and I'm missing something about mapped types?
The text was updated successfully, but these errors were encountered: