我有一个 appState
,我可以用 action
更新它:
type AppState = {
contentWidth: number
mapLayers: string[]
}
type Action = {
[K in keyof AppState]: any
}
例如:
const appState: AppState = {
contentWidth: 0,
mapLayers: [],
}
// will set contentWidth to 200 in appState
const action: Action = {
contentWidth: 200
}
// rest of the implementation
在此之前一切正常。
但现在我想为每个操作添加一个额外的 type
属性。
const action: Action = {
type: 'DISPATCH_CONTENT_WIDTH',
contentWidth: 200,
}
我被卡住了,因为我不知道如何相应地更新 Action
类型。我试过了:
type Action = {
type: string
[K in keyof AppState]: any
}
现在打字稿编译器抱怨:
我应该如何修复该错误?
答案 0 :(得分:0)
这个怎么样? (Playground link)
type State = {
propA: "A"
propB: "B"
}
type KeyMutations<S extends {}> = {
[k in keyof S & string]: {
type: `DISPATCH_${Uppercase<k>}`
value: S[k]
}
}[keyof S & string]
type OtherActions = "Whatever"
type Actions = KeyMutations<State> | OtherActions