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

Typescript: This condition will always return 'false' since the types 'Type' and 'number' have no overlap

I’m learning generics in Typescript and i have a function that first checks the argument passed in, does something, and returns the argument. If i try to check type of the argument there is no problem.

function identity<Type> (arg: Type): Type {
  if (typeof(arg) === 'number') console.log('test');
  return arg;
}

But if i try to compare to argument with a value like:

function identity<Type> (arg: Type): Type {
  if (arg === 5) console.log('test');
  return arg;
}

It throws an error saying:

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

generics.ts:2:6 - error TS2367: This condition will always return 'false' since the types 'Type' and 'number' have no overlap.

2  if (arg === 5) console.log('test')
       ~~~~~~~~~

I don’t understand why it throws an error saying this condition will always return false. It can be true i think, i can pass an argument that is exactly the value i’m checking, and if i can’t compare it with a value i think don’t need to be able compare it with a type either.

>Solution :

This seems like an incorrect TypeScript compiler behavior. It has been fixed in 4.8.4.

Error in 4.7.4: Playground

Fixed in 4.8.4: Playground

If you’re not ready to upgrade, you can fix the issue by refining the type first:

function identity<Type> (arg: Type): Type {
  if (typeof(arg) === "number" && arg === 5) console.log('test', arg);
                                                              // ^? Type & number
  return arg;
}

playground

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