簡體   English   中英

Typescript. 如何獲取枚舉項數據作為類型

[英]Typescript. How to get enum item data as a type

我有一個枚舉類型,例如Currency 我無法更改它,因為它會自動構建在 graphql 架構上。 我想將它用於我的數據,但我不知道該怎么做。

enum Currency {
  rub = 'RUB',
  usd = 'USD',
  eur = 'EUR',
}

const data: { currency: Currency[keyof typeof Currency] } = {
  currency: 'RUB',
};

錯誤

TS2339: Property 'eur' does not exist on type 'Currency'.
TS2339: Property 'rub' does not exist on type 'Currency'.
TS2339: Property 'usd' does not exist on type 'Currency'.

我不確定是否有可能完全按照你想做的去做,但很可能你想做這樣的事情:

const data: { currency: Currency } = {
  currency: Currency.rub,
};

這就是枚舉的典型使用方式(通過在獲取其值之一時始終顯式引用枚舉)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM