简体   繁体   English

TypeScript 类型,仅接受 object 的密钥

[英]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.

相关问题 Typescript object 数组类型声明中的可空键 - Typescript nullable keys in object array type declaration 如何在 TypeScript 中使用备用键正确键入 object? - How to correctly type an object with alternate keys in TypeScript? 如何键入命名的可选参数,该参数接受 object 以及在 TypeScript-React 中具有默认值的可选字段? - How to type named, optional parameter that accepts an object with optional fields that have defaults in TypeScript-React? 是否可以在 TypeScript 上创建一个 object 接口,允许灵活数量/类型的键? - Is it possible to create an object interface on TypeScript that allows a flexible number/type of keys? 如何定义对象的类型以仅接受枚举中的键? - How to define type of an object to accept only keys from enum? 在 React TypeScript 中仅包含 boolean 值的 object 的类型是什么? - What is the type for an object that contains only boolean values in React TypeScript? 如何确保字符串是接受字符串的道具中 object 的键之一? - How to ensure that string is one of the keys of an object in a prop that accepts string? 将类型键映射到字符串,然后映射到Typescript中的字符串类型 - Map type keys to strings and then to a type of strings in Typescript 打字稿中自定义对象的类型 - type of custom object in typescript Object 输入 Typescript - Object Type in Typescript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM