Skip to content

Motivation for a thin Amount versus protocol #24

@sffc

Description

@sffc

I listed the following motivations for thin Amount today at TC39:

  1. Represents a thing that many developers frequently have: a number with unit
    • By representing this, we can offer useful operations like i18n
  2. Improves i18n by moving unit and precision to the data model
    • Fixes the "1.0 Stars" problem (different behavior in Intl.NumberFormat and Intl.PluralRules)
  3. Prerequisite for the MessageFormat proposal (medium-term)
    • MF 2.0 is recommending this type of data model
  4. Prerequisite for the Smart Units proposal (longer-term)
    • To prevent misuse of Intl APIs to do unit conversion

However, it wasn't clear to some delegates what this brings to the table versus a protocol-based approach: for example, adding support for passing { value: 123, unit: "meter" } to Intl.NumberFormat.prototype.format.

We have discussed passing objects to the format function in the past; for example, tc39/proposal-intl-numberformat-v3#1.

A couple key points for me for thin Amount, even without any other prototype functions:

  1. Supports toLocaleString: this mechanism offers an onramp to i18n.
  2. More discoverable: the protocol-based approach can be documented on Intl.NumberFormat.prototype.format and Intl.PluralRules.prototype.format, and we can make tutorials and things to advocate for this pattern, but we are putting aside a big opportunity to nudge developers to represent their data model in code.
  3. Units and currencies can be validated: since we're moving these from constructor to format function, we lose the ability to validate early on. Concrete example: catch misspellings such as metre.
  4. Ergonomic integration with Decimal is possible
  5. More parallel with Temporal and the expectations developers have in the Temporal world.

Anything else to add here?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions