简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM