0

So, I have type alias T which represents string | number union type

if I try to add two variables with this type, I'll get variable with type T. But if I take these two variables as parameters of a function it will be an error:

type T = string | number;

function add(a: T, b: T): T{
  return a + b; 
  // Error: Operator '+' cannot be applied to types 'T' and 'T'.
}

let a: T = 1;
let b: T = 'foo';

const c = a + b; // But this is ok

Why I can't do that?

1

1 Answer 1

0

The error case here is number + number | string

You can verify that as the below function is not valid.

function addOne(x: number | string) {
  return 1 + x;
}

From the typescript github page

If T extends string | number then T can be string | number which means one value of type T can be string a different value of type T can be a number.

It really sounds like you should use overloads here rather than a type parameter.

Sign up to request clarification or add additional context in comments.

1 Comment

But by that definition if both are numbers -- it's ok, if one number and one string -- it's ok. And when you trying to add number and number | string, only these two cases can happen. Seems like typescript not smart enough to figure that out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.