In this illustrative example:
enum Methods {
X = 'X',
Y = 'Y'
}
type MethodProperties = {
[Methods.X]: {
x: string
}
[Methods.Y]: {
y: string
}
}
type Approach = {
[method in keyof MethodProperties]: {
method: method
} & MethodProperties[method]
}
//produces the anticipated outcome, but may not be optimal for every scenario
const strategy1: Approach[Methods] = {
method: Methods.X,
x: 'string',
};
(() => {
if (strategy1.method === Methods.X) {
strategy1.x = 'anotherstring';
//does not throw an error since the compiler recognizes
//the potential properties based on method type
}
})();
//does not generate the expected outcome, but might be more suitable for certain situations
type Plan = {
method: Methods
methodProps: MethodProperties[Plan['method']]
}
const strategy2: Plan = {
method: Methods.X,
methodProps: {
x: 'string',
y: 'string',
}
};
(() => {
if (strategy2.method === Methods.X) {
strategy2.methodProps.x = 'anotherstring';
//results in an error - Property 'x' does not exist on type '{ y: string; }'
}
})();
The desired outcome is to notify the compiler that when state.type === ActionTypes.A
, then the type of state.actionProps
should be ActionProps[ActionTypes.A]
.
Are there any feasible workarounds for this issue?