结合枚举和计算 属性 名称的对象字面量
Object literals combining enums and computed property names
我有一个枚举
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,
};
我想定义一个类型/接口,其键是模板文字,将 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,
}
当我清楚地知道Action
和ActionState
的成员时,如何定义ActionModelState
?编译器抱怨:
Type 'key' cannot be used to index type '{ action1: "actionState1"; action2: "actionState2"; }'
但我认为 typeof key === keyof Action
。我做错了什么?
事实证明,我可以使用 -- Playground.
而不是试图驯服 keyof
type ValueOf<T> = T[keyof T];
type ActionModelState = {
[key in ValueOf<typeof ActionState>]: boolean;
}
我仍然想知道我是否可以使用某种形状或形式的模板文字...
你根本不需要keyof Action
;类型 Action
已经是这些字符串值的并集。所以你想要 key in Action
,而不是 key in keyof Action
。
type ActionModelState = {
[key in Action as `${typeof ActionState[key]}`]: boolean
}
我有一个枚举
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,
};
我想定义一个类型/接口,其键是模板文字,将 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,
}
当我清楚地知道Action
和ActionState
的成员时,如何定义ActionModelState
?编译器抱怨:
Type 'key' cannot be used to index type '{ action1: "actionState1"; action2: "actionState2"; }'
但我认为 typeof key === keyof Action
。我做错了什么?
事实证明,我可以使用
keyof
type ValueOf<T> = T[keyof T];
type ActionModelState = {
[key in ValueOf<typeof ActionState>]: boolean;
}
我仍然想知道我是否可以使用某种形状或形式的模板文字...
你根本不需要keyof Action
;类型 Action
已经是这些字符串值的并集。所以你想要 key in Action
,而不是 key in keyof Action
。
type ActionModelState = {
[key in Action as `${typeof ActionState[key]}`]: boolean
}