JustinM
JustinM

Reputation: 1003

TypeScript won't allow arithmetic operators but I don't understand why

Why does TypeScript give the Operator '+' cannot be applied error in this case? The number types are essentially unchanged. I've got an unusual coding situation where I want to remove the built-in methods on number, like toExponential, but want math operators to still work. Is there some kind of #pragma or something to let this work?

let x: Omit<number, 'banana'> = 1;
let y: Omit<number, 'banana'> = 2;
let z = x + y;

Upvotes: 2

Views: 478

Answers (1)

ruohola
ruohola

Reputation: 24058

The + operator doesn't work on that type. Relevant section from the spec:

4.19.2 The + operator

The binary + operator requires both operands to be of the Number primitive type or an enum type, or at least one of the operands to be of type Any or the String primitive type. Operands of an enum type are treated as having the primitive type Number. If one operand is the null or undefined value, it is treated 84 as having the type of the other operand. If both operands are of the Number primitive type, the result is of the Number primitive type. If one or both operands are of the String primitive type, the result is of the String primitive type. Otherwise, the result is of type Any.

(emphasis mine)

Source: https://javascript.xgqfrms.xyz/pdfs/TypeScript%20Language%20Specification.pdf

Upvotes: 3

Related Questions