1

This seems so trivial, yet I am not understanding why this isn't working. Since I am just concatinating/adding depending on a number or string, the return type should match.

function M<T>(arg: T): T {
  return arg + arg;
}


M(3) // 6
M('bill') // billbill
2
  • What did you want? const a = M<number>(3); // a will be a number, const b = M<string>('bill');// b will be a string Commented Aug 21, 2019 at 6:20
  • See also this issue on the topic github.com/Microsoft/TypeScript/issues/12410 Commented Aug 21, 2019 at 8:53

1 Answer 1

1

There is no type constraint in TypeScript saying a certain operator can be applied to a certain type. So it is not possible to do this.

Something close and valid is:

interface Addable<T> {
    add(that: T): T;
}

function M<T extends Addable<T>>(arg: T): T {
  return arg.add(arg);
}

But there is just no way to express it for an operator, + in this case.

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

2 Comments

typescriptlang.org/play/index.html , doesn't seem to work when used with: M(3) or M(test)
@jamesemanon Certainly it doesn’t. There’s just no way to do that.

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.