循环遍历枚举并填充键为枚举的Typescript记录
我喜欢在Typescript中使用记录的类型安全性,但在循环键枚举和填充记录方面似乎处于困境循环遍历枚举并填充键为枚举的Typescript记录,typescript,enums,Typescript,Enums,我喜欢在Typescript中使用记录的类型安全性,但在循环键枚举和填充记录方面似乎处于困境 export enum Key { A = 'A', B = 'B', C = 'C' } export interface Value { isAvailable: boolean; reasons: string[]; } export type Access = Record<Key, Value>; export function access() {
export enum Key {
A = 'A',
B = 'B',
C = 'C'
}
export interface Value {
isAvailable: boolean;
reasons: string[];
}
export type Access = Record<Key, Value>;
export function access() {
// I would like to avoid this initialization but TS does not allow it because it defeats the
// purpose and makes me initialize a value for each key in the enum upfront.
const featureAccess: Access = {
[Key.A]: null,
[Key.B]: null,
[Key.C]: null,
};
Object.keys(Key).forEach((eachKey: string) => {
const feature = Access[eachKey];
featureAccess[feature] = {
isAvailable: ..., // Populate from API
reasons: ...// Populate from API
};
});
return featureAccess;
}
导出枚举密钥{
A=‘A’,
B=‘B’,
C='C'
}
导出接口值{
isAvailable:布尔值;
原因:字符串[];
}
导出类型访问=记录;
导出函数访问(){
//我希望避免此初始化,但TS不允许,因为它会破坏
//目的并使我预先为枚举中的每个键初始化一个值。
常量特性访问:访问={
[Key.A]:空,
[Key.B]:空,
[Key.C]:空,
};
Object.keys(Key.forEach)((eachKey:string)=>{
const feature=Access[eachKey];
功能访问[功能]={
isAvailable:…,//从API填充
原因:…//从API填充
};
});
返回特性访问;
}
这是使用Typescript记录的错误候选者吗?这个问题可能已经问了很长时间,但如果有人想知道答案,我们可以用它来回答 或者我们也可以使用枚举值
const featureAccess: Access = {};
Object.values(Key).forEach((enumValue) => {
console.log(enumValue);
featureAccess[enumValue] = ..... // assign the value
});
您至少可以通过使用
任何
类型使其工作
导出函数访问(){
const featureAccess:any={};
Object.keys(Key.forEach)((eachKey:string)=>{
const feature=Access[eachKey];
功能访问[功能]={
isAvailable:…,//从API填充
原因:…//从API填充
};
});
将featureAccess返回为Access;
}
这是我发现的避免记录类型为可选(即
记录
)的唯一方法。通过any
感觉像是一个黑客,所以我希望能有所改进。为什么不type Key='a'|'B'|'C'代码>?然后Object.keys(featureAccess)
如果需要,我会准备一个答案对不起,我没有听清楚。你能把答案放在这里吗?转换为联合类型在这里有什么帮助?唱片公司仍将尝试寻找不同的可能性,对吗?
const featureAccess: Access = {};
Object.keys(Key).forEach((enumKey) => {
console.log(enumKey);
featureAccess[enumKey] = ..... // assign the value
});
const featureAccess: Access = {};
Object.values(Key).forEach((enumValue) => {
console.log(enumValue);
featureAccess[enumValue] = ..... // assign the value
});