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 database ETypeId.alpha
is how I access it in my code "Alpha"
is what gets displayed to the user. Agree with Sergi Dote Teixidor's answer that Map is the best option for such problem. However, based on the described problem, I think that it could be simplified to Map<ETypeId, string>
:
enum ETypeId {
alpha = "a",
beta = "b"
}
const types: Map<ETypeId, string> = new Map( [
[ ETypeId.alpha, "Alpha" ],
[ ETypeId.beta, "Beta" ],
]);
Just in case you want to initialize your structure once and make TypeScript protect you from changing values inside your map:
enum ETypeId {
alpha = "a",
beta = "b"
}
interface ReadonlyMap<TKey, TValue> {
get(key: TKey):TValue;
}
const types: ReadonlyMap<ETypeId, string> = new Map( [
[ ETypeId.alpha, "Alpha" ],
[ ETypeId.beta, "Beta" ],
]);
// Static analyzer error if you try to change the value:
types.set(ETypeId.alpha, "NewValue");
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"}
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.