I have a simple code which checks property for null and throws exception if it is null or returns the value.
functiongetNonNull<Textendsobject,KextendskeyofT>(obj: T,key: K): T[K]{constv=obj[key];if(v!=null){returnv;}else{throw"A";}}The only catch that it doesn't say it returns non-null value.
consta=getNonNull({a:null},"a");// a : nullI 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.
functiongetNonNull<U,Textends{[Kinstring]: U|null|undefined},KextendskeyofT>(obj: T,key: K): T[K]{constv=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'.returnv;}else{throw"A";}}Do I miss something ?
I have a simple code which checks property for null and throws exception if it is null or returns the value.
The only catch that it doesn't say it returns non-null value.
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.
Do I miss something ?