我有一个减速器在反应。动作可以是8种类型中的一种,但为了简单起见,让我们假设只有2种类型
type Add = {
type: 'add';
id: string;
value: string;
}
type Remove = {
type: 'remove';
id: string;
}
type Action = Add | Remove;
我没有使用switch用例,而是使用了一个处理程序对象,其中每个处理程序都是一个处理特定操作的函数
const handlers = {
add: (state, action) => state,
remove: (state, action) => state,
default: (state, action) => state,
}
const reducer = (state, action) => {
const handler = handlers[action.type] || handlers.default;
return handler(state, action);
}
现在我想键入
handlers
对象。因此,处理程序函数应该接受与它在
处理程序
对象
type Handlers = {
[key in Action["type"]]: (state: State, action: Action) => State
// âthis here should be the action which has type
// matching to it's key. So when the key is
// 'add', it should be of type Add, and so on.
}
我所能想到的就是明确地声明键和匹配的操作类型。有没有办法根据键的值从并集中“挑选”类型?