Pål Thingbø
Pål Thingbø

Reputation: 1301

How to assign union values to object array in Typescript

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

Upvotes: 0

Views: 63

Answers (1)

vighnesh153
vighnesh153

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

Related Questions