Skip to content

Don't allow math operations on different branded numeric typesΒ #59423

Open
@JoshuaKGoldberg

Description

@JoshuaKGoldberg

πŸ”Ž 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

https://www.typescriptlang.org/play/?#code/C4TwDgpgBAwgrgJwRAdgYxAHgCoD4oC8UKcAtgEYQJQBkUA3lAPpNqLLogBcU2UAvgG4AUKEhQAoogD2hWO1QZMAIggzluEWOgBVAMoAROfCSKsyuAGcAJhpHCAZnHTAAltJRQ0AQxQAFRDQAC29LCABJYAhSAAowBFc0CJQpBGkeVOkAGigAd28AGwKIYHCUfQMeCoBKBmEoBqgAeiaoADlZbSgqNIQc8jhgKHC86TgC6ygQgDdoCAAPSDQoyY8IesbkYERPfKKSsoqofHjE5MyRfmEgA

πŸ’» 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 });

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions