簡體   English   中英

在界面中使用枚舉的打字稿

[英]Typescript using enum within an interface

我是Typescript的新手,我不確定語法。 我嘗試在線搜索,但沒有找到任何有用的東西。

這些是我的接口和枚舉定義。

interface Products {
    asian: {[key: string]: string};
    american: {[key: string]: string};
}

enum State {
   NEWYORK = 'nyc',
   BOSTON = 'boston'
}

interface Branch {
   nyc: {
     products: Products;
   };
   boston: {
      products: Products;
   };
}

我不知道如何在Branch接口中使用Enum State 這樣我就可以使用STATE.NEWYORKSTATE.BOSTON枚舉。 像這樣的東西:

interface Branch {
   State.NEWYORK: {
     products: Products;
   };
   STATE.BOSTON: {
      products: Products;
   };
}

謝謝閱讀。

您可以使用計算屬性的語法:

interface Branch {
   [State.NEWYORK]: {
     products: Products;
   };
   [State.BOSTON]: {
      products: Products;
   };
}

但是請注意,即使您使用enum值,索引器仍是字符串和值為0,中enum使用。 所以這些都是有效的:

let f!: Branch;
f[State.NEWYORK]
f["nyc"]
f.nyc

演示

暫無
暫無

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

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