Home > Software engineering >  Typescript: This condition will always return 'false' since the types 'Type' and
Typescript: This condition will always return 'false' since the types 'Type' and

Time:10-01

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:

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.

CodePudding user response:

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

  • Related