Closed
Description
I have a simple code which checks property for null and throws exception if it is null or returns the value.
function getNonNull<T extends object, K extends keyof T>(obj: T, key: K): T[K] {
const v = obj[key];
if (v != null) {
return v;
} else {
throw "A";
}
}
The only catch that it doesn't say it returns non-null value.
const a = getNonNull({a:null},"a"); // a : null
I am trying to improve function to set 'obj' as an object of type [K in string]: U | null | undefined and then TypeScript would return 'U'.
Unfortunately TypeScript doesn't like it and types 'U' as '{}' instead of correct type.
function getNonNull<
U,
T extends {[K in string]: U | null | undefined },
K extends keyof T
>(obj: T, key: K): T[K] {
const v = obj[key];
if (v != null) {
// error TS2322: Type 'T[K]' is not assignable to type 'U'.
// Type 'U | null | undefined' is not assignable to type 'U'.
// Type 'undefined' is not assignable to type 'U'.
return v;
} else {
throw "A";
}
}
Do I miss something ?