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.alphais how I access it in my code"Alpha"is what gets displayed to the user.