0

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;
}

enter image description here

1 Answer 1

6

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.