0

I don't know if this is really possible, but I have an existing object that maps string keys to React components.

I want to create a type to essentially make a parent component only accept keys of the icon mapping object as a prop:

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.

3
  • Wait, what's the purpose of Object.freeze({}) here? You have ensured that icons has no properties at all. Assuming you don't want type IconProps = {name: never} I think it would useful if you could modify the code so as to constitute a minimal reproducible example .Good luck. Commented Jan 21, 2021 at 2:01
  • The general idea is to use keyof. But agree with @jcalz that we need a minimal example in order to help. Commented Jan 21, 2021 at 4:46
  • sorry that the example was unclear. icons would be the object that’d map a string key to a react component. for example const icons = Object.freeze({ Add: () => /* svg /* }). the object is frozen such that it’s immutable to consumers Commented Jan 21, 2021 at 17:46

1 Answer 1

1

In this case, you need to create an enum(IconName) to see the names of the icons and assign this to the key.


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:

type IconProps = {
  name: IconName
}

export const Icon: React.VFC<IconProps> = ({ name }) => {
  // on this return you need to return only the value.  
  return icons[name]; 
}
Sign up to request clarification or add additional context in comments.

1 Comment

feels bad. i was hoping i could do it without duplicating key names

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.