I am getting this error, Where as U is number and returning the number too.
Type 'number' is not assignable to type 'U'.
function foo<T extends string, U extends number>(a: T): U {
return +a; // error in this line
}
foo<string, number>('12')
>Solution :
I believe it worth using overloading here:
type UnsafeNumber = number & { tag?: 'UnsafeNumber' }
type ParseInt<Str extends string> =
Str extends `${infer Digit extends number}`
? Digit
: UnsafeNumber
function foo<T extends string>(a: T): ParseInt<T>
function foo<T extends string>(a: T) {
return +a;
}
type Result = ParseInt<'.2'>
const _ = foo('42') // 42
const __ = foo('4.2') // 4.2
const ___ = foo('s03') // UnsafeNumber
Since TS does not distinguish number and NaN I have provided UnsafeNumber which corresponds to NaN. However, it is still not safe and I would recommend you to use parseItn function