Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript using enum within an interface

Tags:

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.

like image 588
Aniks Avatar asked Apr 13 '18 14:04

Aniks


People also ask

Can we use enum in interface TypeScript?

Enums or enumerations are a new data type supported in TypeScript. Most object-oriented languages like Java and C# use enums. This is now available in TypeScript too. In simple words, enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values.

Can you put an enum in an interface?

It's perfectly legal to have an enum declared inside an interface . In your situation the interface is just used as a namespace for the enum and nothing more. The interface is used normally wherever you use it.

Can I use enum as a type in TypeScript?

In TypeScript, enums, or enumerated types, are data structures of constant length that hold a set of constant values. Each of these constant values is known as a member of the enum. Enums are useful when setting properties or values that can only be a certain number of possible values.

Can TypeScript interface have methods?

A TypeScript Interface can include method declarations using arrow functions or normal functions, it can also include properties and return types. The methods can have parameters or remain parameterless.


1 Answers

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

like image 194
Titian Cernicova-Dragomir Avatar answered Sep 28 '22 19:09

Titian Cernicova-Dragomir