【问题标题】:TS create keys of new type from array of stringsTS 从字符串数组创建新类型的键
【发布时间】:2021-10-24 19:01:42
【问题描述】:

我只是想维护一个动态扩展 FiatExchangeRates 类型定义的值数组。

知道如何解决这个问题吗?

const currencies = ['eur', 'usd', 'gbp', 'chf'] as const;

type FiatExchangeRates = {
    // ... how to get the following?
    // eur: number,
    // usd: number,
    // gbp: number,
    // chf: number,
}

const fiatExchangeRates: FiatExchangeRates = {
  eur: 1.11,
  usd: 1.12,
  gbp: 1.13,
  chf: 1.14,
};

const a = fiatExchangeRates.eur;

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以提取tuple member type 并使用mapped type 创建所需的:

    type FiatExchangeRates = { [K in (typeof currencies)[number]] : number }
    

    Playground

    【讨论】:

    • 哇,感谢您的快速回复:)
    • 你知道将currencies const 转换成这样的新类型:type Currency = 'eur' | 'usd' | 'gbp' | 'chf'
    • type Currency = (typeof currencies)[number] 已经是答案的一部分?。 type FiatExchangeRates = { [C in Currency]: number }
    • coooool :) 谢谢
    猜你喜欢
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多