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