Reputation: 1301
How can the setState()
function be designed when assigning union typed values to the object array?
enum SomeStateEnum {
IsRunning,
Name,
}
type PersonState = {
[SomeStateEnum.IsRunning]: boolean;
[SomeStateEnum.Name]: string;
};
const state: PersonState = {
[SomeStateEnum.IsRunning]: false,
[SomeStateEnum.Name]: 'John Doe',
};
function setState(key: SomeStateEnum, value: boolean | string) {
state[key] = value;
}
Upvotes: 0
Views: 63
Reputation: 5388
You need to make sure that the value you are assigning with, should match the value type of the key.
function setState<T extends SomeStateEnum>(key: T, value: PersonState[T]) {
state[key] = value;
}
Upvotes: 6