在某些庫中,我經常看到類似這樣的 TS 語法:
輸入 AriaRole = | '警報' | '樹' | '樹形網格' | '樹項' | (細繩 & {});
什么意思string & {}?
它是一個與物件相交的字串。
這是否有意義或可能是一個黑客?
uj5u.com熱心網友回復:
看起來很奇怪,因為這種型別基本上是string.
但是如果你寫了'alert' | 'tree' | 'treegrid' | 'treeitem' | string那么你的型別將被簡化為string. 這意味著如果您開始撰寫此代碼:
let role: AriaRole = 'a
那么你不一定會得到有用的自動完成建議。就 Typescript 而言,AriaRole如果string您只撰寫任何字串,Typescript 不知道這些特定字串值得建議。
但隨著寫string & {},它不會簡化成string等全聯盟沒有得到簡化,并且其結果是,你得到自動完成建議'alert','tree'或等等,同時還允許其他任何字串值。
因此,我認為以這種方式撰寫型別的原因是擁有一種允許每個字串的型別,但自動完成建議會“鼓勵”某些字串。這也意味著當您將滑鼠懸停在型別名稱上時,您可以看到那些“鼓勵”的字串。
uj5u.com熱心網友回復:
致@AlekseyL 和@kaya3
所以這是實作(string & {}):
type Theme = 'primary'|'secondary'|'success'|'danger'|(string & {})
interface MyComponentProps {
theme? : Theme
}
export default function MyComponent(props: MyComponentProps) => ....
<MyComponent theme='primary' /> // choose from the pre defined themes
<MyComponent theme='customDark' /> // or use a custom theme name
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/343882.html
標籤:打字稿
