In TypeScript, in an array or similar data structure, how can I map a string to an id, while ensuring that only a certain range of ids is allowed?
Here is what I want to do. This works fine. However, I am wondering if there is a more concise way of achieving this?
enum ETypeId {
alpha = "a",
beta = "b",
gamma = "g"
}
interface IType {
id: ETypeId,
title: string,
}
myTypes: IType[] = [
{ id: ETypeId.alpha, title: "Alpha" },
{ id: ETypeId.beta, title: "Beta" },
{ id: ETypeId.gamma, title: "Gamma" }
];
As is, I have to do the following to get from the id
to the title
:
function getTypeForTypeId( typeId: ETypeId ): IType {
return myTypes.find( type => type.id == typeId );
}
Can I use a different data structure that makes some of the above code more concise, or is this already as good as it gets?
Explanation:
"a"
is what gets stored in my databaseETypeId.alpha
is how I access it in my code"Alpha"
is what gets displayed to the user.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.
Enums allow us to define or declare a collection of related values that can be numbers or strings as a set of named constants. Unlike some of the types available in TypeScript, enums are preprocessed and are not tested at compile time or runtime.
You can map the enum value to a String. This mapping is not as efficient, but you can add or remove enum values without any side effects.
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.
you can use a map:
example:
enum ETypeId {
alpha = "a",
beta = "b",
gamma = "g"
}
interface IType {
id: ETypeId,
title: string,
}
const myMap: Map<string, IType> = new Map( [
[ ETypeId.alpha, { id: ETypeId.alpha, title: "Alpha" } ],
[ ETypeId.beta, { id: ETypeId.beta, title: "Beta" } ],
[ ETypeId.gamma, { id: ETypeId.gamma, title: "Gamma" } ]
]);
console.log(myMap.get(ETypeId.alpha)) // -> {id: "a", title: "Alpha"}
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