Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generic function Type 'number' is not assignable to type 'U'

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Playground

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading