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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With