我有一个枚举
enum Action {
action1 = 'action1',
action2 = 'action2'
};
我将其值用作对象中的计算属性名称:
/*
...to be able to use these as values, not just types
*/
const ActionState = {
[Action.action1]: 'actionState1' as const,
[Action.action2]: 'actionState2' as const,
};
我想定义一个类型/一个接口,其键是将 an 映射Action
到相应的模板文字ActionState
:
/*
{
actionState1: boolean;
actionState2: boolean;
}
*/
type ActionModelState {
[key in keyof Action as `${typeof ActionState[key]}`]: boolean // all booleans but I need the keys to be restricted
}
// throwing:
// Type 'key' cannot be used to index type '{ action1: "actionState1"; action2: "actionState2"; }'.
我将用它扩展我的基本类型:
type BaseAction = {
id: number;
foo: string;
bar: string;
};
来形成:
type EnrichedAction = BaseAction & ActionModelState;
最终得到:
const enrichedAction: EnrichedAction = {
id: 123,
foo: 'foo',
bar: 'bar',
actionState1: true,
actionState2: false,
}
ActionModelState
当我清楚地知道Action
as的成员时,我该如何定义ActionState
?编译器抱怨说:
类型 'key' 不能用于索引类型 '{ action1: "actionState1"; 动作2:“动作状态2”;}'
但我想typeof key === keyof Action
。我究竟做错了什么?
你根本不需要keyof Action
这里;类型Action
已经是这些字符串值的联合。所以你想要key in Action
,不是key in keyof Action
。
type ActionModelState = {
[key in Action as `${typeof ActionState[key]}`]: boolean
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句