Open
Description
π Search Terms
number numeric branded types plus minus add subtract
π Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about Nominal types (tagged, branded)
β― Playground Link
π» Code
type Currency<T> = number & { __currency: T };
type Euro = Currency<"euro">;
type USD = Currency<"usd">;
function canPurchaseItem(priceInEuro: Euro, walletInUSD: USD) {
// No type error, but I would have expected one
return walletInUSD > priceInEuro;
}
π Actual behavior
Euro
and USD
-two different branded numeric types- can be compared with binary operators such as -
.
π Expected behavior
These are two different branded numeric types. I would have expected that binary operations between the two of them would be disallowed.
More technically, if a mathematical binary operation contains:
- one value that is an intersection of
number
and some object type - another value that is not assignable to that type
...then I'd expect to receive a type error.
Additional information about the issue
Per #202, TypeScript doesn't actually formally include a built-in branded/nominal typing. But other mismatched operators are disallowed [playground of mismatched operators]:
// These are all type errors:
console.log([] + []);
console.log([] + {});
console.log([] + 1);
console.log({} + 1);
console.log({} + {});
console.log({ a: 1 } + { b: 2 });