简体   繁体   中英

Typescript using enum within an interface

I am new to Typescript and I am not sure about the syntax. I tried searching online but didn't find anything helpful.

These are my interfaces and enum definitions.

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

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

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

I am not sure how to use the Enum State inside Branch interface. So that I can use STATE.NEWYORK and STATE.BOSTON Enums. Something like this:

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

Thanks for reading.

You can use the syntax for computed properties:

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

Note though that even though you use the enum values, the indexer is still string and the value o of the enum is used. So any of these will be valid:

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

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM