我有一個enum
enum Action {
action1 = 'action1',
action2 = 'action2'.
};
在一個物件中,我把它們的值作為計算的屬性名:
/*
...能夠將這些作為值使用,而不僅僅是型別
*/
const ActionState = {
[Action.action1] 。'actionState1' as const。
[Action.action2] 。'actionState2' as const。
};
我想定義一個型別/介面,其鍵是模板字,將一個Action映射到相應的ActionState:
/*
{
actionState1: boolean;
actionState2: 布林值。
}
*/
型別 ActionModelState {
[key in keyof Action as `${typeof ActionState[key]}`] 。boolean // all booleans but I need the keys to be restricted .
}
//拋出:。
///型別'key'不能用于索引型別'{ action1: "actionState1"; action2: "actionState2"; }'。
我將用它來擴展我的基本型別:
type BaseAction = {
id: 數字。
foo: string;
bar: string;
};
對表格:
type EnrichedAction = BaseAction & ActionModelState;
最后是:
const enrichedAction。EnrichedAction = {
id: 123,
foo: 'foo',
bar: 'bar'。
actionState1: true,
actionState2: false,
當我清楚地知道Action以及ActionState的成員時,我怎樣才能定義ActionModelState?編譯器抱怨說:
但是我想typeof key === keyof Action。我做錯了什么?
uj5u.com熱心網友回復:
你在這里根本不需要keyof Action;Action型別已經是這些字串值的聯合。所以你需要key in Action,而不是key in keyof Action。
type ActionModelState = {
[key in Action as `${typeof ActionState[key]}`] 。boolean
}
uj5u.com熱心網友回復:
事實證明,與其試圖馴服keyof,不如使用ValueOf幫助器 -- Playground。
type ValueOf<T> = T[keyof T]。
型別ActionModelState = {
[key in ValueOf<typeof ActionState>] : boolean;
}
我仍然想知道我是否可以以某種形式使用模板字面......
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/332481.html
標籤:
