Sometimes based on code I know what return value will be and want to specify it using:
getSmth<string>(1)
and not
getSmth(1) as string
but not sure how to do it correctly
- Problem. Why there is errors if i extend and return correctly?
Type 'null' is not assignable to type 'T'.
'null' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | null'.(2322)
Example
const getName = (id: number) : string | null => null
const getSmth = <T extends string | null = string | null>(id: number | null): T => {
if (!id) {
return null;
}
return getName(id);
};
const x1 = getSmth(1) // should be string | null
const x2 = getSmth<null>(1) // should be null
const x3 = getSmth<string>(1) // should be string
- Question. Why this assertion happening?
const getSmth2 = <T extends string | null = string | null>(id: number | null): T => {
if (!id) {
return null as T;
}
return getName(id) as T;
};
const y1: string = getSmth2(1) // why getSmth2 asserts to string when return type should bestring | null
unknownkeyword. This will force the next user to apply a type when it is not available, pls refer : stackoverflow.com/questions/51439843/unknown-vs-any for more detailsgetNameexpects number but you want to pass astring<T extends string | null = string | null>(id: number | null): Tmakes very little sense; it means I can callgetSmth<'foobar'>(5)and the emitted Javascript code - in which the string'foobar'is not even present - is supposedly guaranteed to return'foobar'(or raise an exception). AndgetSmth<'baz'>(5)is supposed to return the string'baz'despite compiling to the exact same Javascript code. The compiler is telling you your code is wrong because your code is wrong.