[英]Simple approach to using TypeScript to specify all properties of object are of type string
我有以下行动 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'
}
而且我想指定它只能允许类型为字符串的属性。 我不知道该怎么做,这就是我不建议尝试的原因。
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'
}
或使用Record<keys, 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'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.