【发布时间】:2020-02-16 17:56:49
【问题描述】:
考虑下一个例子:
enum ActionTypes {
A = 'A',
B = 'B'
}
type ActionProps = {
[ActionTypes.A]: {
a: string
}
[ActionTypes.B]: {
b: string
}
}
type Action = {
[type in keyof ActionProps]: {
type: type
} & ActionProps[type]
}
//produces the expected result, but not ideal for the case
const state1: Action[ActionTypes] = {
type: ActionTypes.A,
a: 'string',
};
(() => {
if (state1.type === ActionTypes.A) {
state1.a = 'anotherstring';
//doesn't error, because the compiler knows
//the possible properties by state.type
}
})();
//doesn't produce the expected result, but it would be ideal for the case
type State = {
type: ActionTypes
actionProps: ActionProps[State['type']]
}
const state2: State = {
type: ActionTypes.A,
actionProps: {
a: 'string',
b: 'string',
}
};
(() => {
if (state2.type === ActionTypes.A) {
state2.actionProps.a = 'anotherstring';
//errors - Property 'a' does not exist on type '{ b: string; }'
}
})();
预期的结果是,如果编译器知道state.type === ActionTypes.A,它就知道state.actionProps 的类型是ActionProps[ActionTypes.A]。
是否有任何可能的解决方法?
【问题讨论】:
-
我不明白“产生了预期的结果,但不适合这种情况”。为什么不理想?如果你想要这种基于控制流的缩小范围,你需要一个有区别的联合,
Action[keyof ActionProps]正是正确的类型。那么有什么不适合你呢?
标签: javascript typescript types