Gass
Gass

Reputation: 9344

Simple approach to using TypeScript to specify all properties of object are of type string

I have the following ACTIONS object

const ACTIONS = {
  FETCH_ERROR: 'API fetch error',
  ACTIVATE_QUIZ: 'activate quiz',
  ACTIVATE_RESULTS: 'activate results',
  CHECK_ANSWER: 'check current answer',
  NEXT_QUESTION: 'go to next question',
  DEACTIVATE_QUIZ: 'deactivate quiz',
  UPDATE_DATA: 'update all the data',
  RESET_STATE: 'reset all the state'
}

And I want to specify that only properties of type string can be allowed in it. I have no idea of how to this, that's the reason I'm not proposing an attempt.

Upvotes: 0

Views: 49

Answers (1)

Jaye Renzo Montejo
Jaye Renzo Montejo

Reputation: 1862

const ACTIONS: { [key: string]: string } = {
  FETCH_ERROR: 'API fetch error',
  ACTIVATE_QUIZ: 'activate quiz',
  ACTIVATE_RESULTS: 'activate results',
  CHECK_ANSWER: 'check current answer',
  NEXT_QUESTION: 'go to next question',
  DEACTIVATE_QUIZ: 'deactivate quiz',
  UPDATE_DATA: 'update all the data',
  RESET_STATE: 'reset all the state'
}

or use Record<keys, type> utility type:

const ACTIONS: Record<string, string> = {
  FETCH_ERROR: 'API fetch error',
  ACTIVATE_QUIZ: 'activate quiz',
  ACTIVATE_RESULTS: 'activate results',
  CHECK_ANSWER: 'check current answer',
  NEXT_QUESTION: 'go to next question',
  DEACTIVATE_QUIZ: 'deactivate quiz',
  UPDATE_DATA: 'update all the data',
  RESET_STATE: 'reset all the state'
}

Upvotes: 3

Related Questions