[英]Map type keys to strings and then to a type of strings in Typescript
我正在嘗試創建一個React組件來擴展Github在@githubprimer/octicons-react
提供的Octicons圖標庫。
庫的導出之一是iconsByName
類型,它看起來像這樣:
type iconsByName = {
'alert': Icon<16, 16>,
'arrow-down': Icon<10, 16>,
'arrow-left': Icon<10, 16>,
'arrow-right': Icon<10, 16>,
...
}
在我的組件中,我想創建一個界面,該界面帶有一個icon
prop,並根據iconsByName
導出的鍵動態生成一個列表。 最后,我的界面應類似於:
接口Octicon
Props {
icon: "alert" | "arrow-down" | "arrow-left" | "arrow-right" | ...;
}
但是我無法使用Object.keys(iconsByName)
生成該列表。 如何以編程方式創建類型,然后傳遞給接口?
您可以使用keyof
類型運算符來獲取一個類型的所有鍵的並集:
type iconsByName = {
'alert': Icon<16, 16>,
'arrow-down': Icon<10, 16>,
'arrow-left': Icon<10, 16>,
'arrow-right': Icon<10, 16>,
}
interface Props {
icon: keyof iconsByName
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.