[英]Typescript enum, interface and mapping
在TypeScript中,在数组或类似的数据结构中,如何将字符串映射到id,同时确保只允许一定范围的id?
这就是我想要做的。 这很好用。 但是,我想知道是否有更简洁的方法来实现这一目标?
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" }
];
按原样,我必须执行以下操作才能从id
到title
:
function getTypeForTypeId( typeId: ETypeId ): IType {
return myTypes.find( type => type.id == typeId );
}
我可以使用不同的数据结构,使上面的代码更简洁,或者这已经很好了吗?
说明:
"a"
是存储在我的数据库中的内容 ETypeId.alpha
是我在代码中访问它的方式 "Alpha"
是向用户显示的内容。 同意Sergi Dote Teixidor的回答, Map是这类问题的最佳选择。 但是,基于所描述的问题,我认为它可以简化为Map<ETypeId, string>
:
enum ETypeId {
alpha = "a",
beta = "b"
}
const types: Map<ETypeId, string> = new Map( [
[ ETypeId.alpha, "Alpha" ],
[ ETypeId.beta, "Beta" ],
]);
如果您想要初始化一次结构并使TypeScript保护您不要更改地图中的值:
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");
你可以使用地图:
例:
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"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.