Microsoft/TypeScript

Intl.NumberFormat does not model required properties when `style` is set to `currency`

Open

#57,514 创建于 2024年2月23日

在 GitHub 查看
 (1 评论) (2 反应) (0 负责人)TypeScript (6,726 fork)batch import
BugDomain: lib.d.tsHelp Wanted

仓库指标

Star
 (48,455 star)
PR 合并指标
 (平均合并 6天 17小时) (30 天内合并 9 个 PR)

描述

⚙ Compilation target

ESNext

⚙ Library

ESNext

Missing / Incorrect Definition

According to the MDN docs, when style is set to currency, then the currency property must be provided.

This could be achieved through a discriminating union on the style property e.g.

interface NumberFormatParamsStyleDecimal {
    style: "decimal"
}

interface NumberFormatParamsStyleCurrency {
    style: "currency"
    currency: string
}

type NumberFormatParams = NumberFormatParamsStyleDecimal | NumberFormatParamsStyleCurrency;

const numberFormat = (params: NumberFormatParams) => {};

numberFormat({
    style: "decimal",
})

numberFormat({
    style: "currency",
    currency: "USD"
})

Sample Code

This fails at runtime, but does not fail compilation:

new Intl.NumberFormat("en", {
    style: "currency",
    currency: undefined
});
VM159:1 Uncaught TypeError: Currency code is required with currency style.
    at new NumberFormat (<anonymous>)
    at <anonymous>:1:1

Documentation Link

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#style

贡献者指南