[英]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.