我正在尝试创建一个 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
的接口(interface)prop 并根据 iconsByName
的键动态生成一个列表导出。最后,我的界面应该类似于:
Octicon界面
Props {
icon: "alert" | "arrow-down" | "arrow-left" | "arrow-right" | ...;
}
但我不能使用Object.keys(iconsByName)
生成该列表。如何以编程方式创建类型然后传递到接口(interface)中?
最佳答案
您可以使用 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
}
关于javascript - 将类型键映射到字符串,然后映射到 Typescript 中的字符串类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52865087/