Home > Software engineering >  Simple approach to using TypeScript to specify all properties of object are of type string
Simple approach to using TypeScript to specify all properties of object are of type string

Time:03-06

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.

CodePudding user response:

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'
}
  • Related