3 回答

TA貢獻1895條經(jīng)驗 獲得超3個贊
TypeScript 3.4的更新:
TypeScript 3.4附帶了更簡潔的語法,稱為“ const contexts”。它已經(jīng)合并到master中,因此在PR中應該可以立即使用。
此功能將使通過使用as constor <const>關鍵字創(chuàng)建不可變(恒定)元組類型/數(shù)組成為可能。由于無法修改此數(shù)組,因此TypeScript可以安全地采用較窄的文字類型,['a', 'b']而不是較寬的類型,('a' | 'b')[]甚至string[]可以忽略該類型,并且我們可以跳過對tuple()函數(shù)的調用。
提及你的問題
但是,問題在于常量ALL_SUITS的類型簽名為('hearts'|'diamonds'|'spades'|'clubs')[]。 (...寧可這樣) ['hearts','diamonds','spades','clubs']
使用新的語法,我們可以準確地實現(xiàn)以下目標:
const ALL_SUITS = <const> ['hearts', 'diamonds', 'spades', 'clubs'];
// or
const ALL_SUITS = ['hearts', 'diamonds', 'spades', 'clubs'] as const;
// type of ALL_SUITS is infererd to ['hearts', 'diamonds', 'spades', 'clubs']
有了這個不可變的數(shù)組,我們可以輕松地創(chuàng)建所需的聯(lián)合類型:
type Suits = typeof ALL_SUITS[number]
- 3 回答
- 0 關注
- 1463 瀏覽
添加回答
舉報