[英]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.