Typescript:來自元組數組的動態列表,沒有交集
P粉163951336
P粉163951336 2023-08-31 23:02:45
0
1
411
<p><pre class="brush:php;toolbar:false;">const intents = ["primary", "secondary", "accent", "danger"] 或 constt; const buttonSizes = ["small", "medium", "big"] as const; type IntentType = (typeof intents)[number]; type SizeType = (typeof buttonSizes)[number]; type ButtonProps = { intent?: IntentType; size?: SizeType; } & { [K in IntentType as `${Lowercase<K>}`]?: boolean; };</pre> <p>在這段程式碼中,我希望 Vue 元件能夠接收以下屬性 </p> <p>或者 喜歡 </p> <p>now, if I write the code more statically, 讚:</p> <pre class="brush:php;toolbar:false;">type ButtonProps = { intent?: "primary" | "secondary" | "accent" | "danger"; size?: "small" | "medium" | "big"; primary?: boolean; secondary?: boolean; accent?: boolean; danger?: boolean; }</pre> <p>它有效......但是我還有一些其他程式碼需要迭代意圖選項,並且只是讓它一直重複......</p> <p>第一個範例有效,但由於某些原因 VUE 拋出錯誤</p> <blockquote> <p>內部伺服器錯誤:[@vue/compiler-sfc] 類型參數傳遞給 DefineProps() 必須是文字類型或對介面的引用 或文字類型。 </p> </blockquote> <p>這個錯誤似乎是已知的並且正在解決,所以看起來</p> <p>在不使用交集的情況下更動態地定義 ButtonProps 的其他方法是什麼? </p>
P粉163951336
P粉163951336

全部回覆(1)
P粉384244473

鑑於錯誤顯示“引用介面或文字類型”,我假設將 ButtonProps 定義為擴展基本類型的介面應該有效:

type IntentAndSize = {
  [K in IntentType as `${Lowercase<K>}`]?: boolean;
};

interface ButtonProps extends IntentAndSize {
  intent?: IntentType;
  size?: SizeType;
}

遊樂場

#
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!