[英]TypeScript type that only accepts keys of an object
I don't know if this is really possible, but I have an existing object that maps string keys to React components.我不知道这是否真的可能,但我有一个现有的 object 将字符串键映射到 React 组件。
I want to create a type to essentially make a parent component only accept keys of the icon mapping object as a prop:我想创建一个类型以使父组件仅接受图标映射 object 的键作为道具:
export const icons: { readonly [key: string]: React.VFC } = Object.freeze({})
type IconProps = {
name: // every key of `icons`
}
export const Icon: React.VFC = ({ name }) => {
return icons[name]({})
}
Again, I don't know if this even is possible, but it'd be super awesome if it was.再说一次,我不知道这是否可能,但如果是的话,那就太棒了。
Also, if you have suggestion for a different title to make it more searchable and descriptive of what I'm actually trying to accomplish, I'd love to update it.此外,如果您建议使用不同的标题以使其更易于搜索和描述我实际想要完成的工作,我很乐意更新它。
In this case, you need to create an enum
(IconName) to see the names of the icons and assign this to the key.在这种情况下,您需要创建一个
enum
(IconName) 来查看图标的名称并将其分配给键。
type IconName = 'homeIcon' | 'ballIcon';
type IconMap = {
[key in IconName]?: React.VFC;
};
const icons: IconMap = {
homeIcon: <ExampleComponent />,
ballIcon: <ExampleComponent />
};
To see this type on the parent component you need to put the IconName
type into the component Generics , like this:要在父组件上查看此类型,您需要将
IconName
类型放入组件Generics中,如下所示:
type IconProps = {
name: IconName
}
export const Icon: React.VFC<IconProps> = ({ name }) => {
// on this return you need to return only the value.
return icons[name];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.