2

Lets say I want to make a library of icons for react+typescript. As for example lets consider only 2 icons in this library: Apple and Banana.

I want to be able to import them separately as the following:

import { Apple } from 'icons'

class MyComponent extends React.Component {
  render() {
    return <Apple/>
  }
}

Now lets consider a case when each icon has its own set of props:

type Props = {}
class Apple extends React.Component<Props> {
}
type Props = {}
class Banana extends React.Component<Props> {
}

Is there a way I can export these props separately through their components? Like this:

import { Apple } from 'icons'

class MyComponent extends React.Component<Apple.Props> {
  render() {
    // passing all the props into the apple
    return <Apple {...this.props}/>
  }
}
1
  • I guess you could do something ugly with a namespace Apple { type Props = {} } but I wouldn't recommend it. Commented Dec 26, 2020 at 20:32

2 Answers 2

2

See answer to similar issue.

Try

import { ComponentProps } from 'react';

class MyComponent extends React.Component<ComponentProps<typeof Apple>> {
  render() {
    return <Apple {...this.props} />
  }
}

Note that this assumes that the imported Apple is a valid react component.

Also consider looking into this typescript cheatsheet for react to have a good grasp of what typescript can do for react.

Sign up to request clarification or add additional context in comments.

Comments

1

In addition to exporting the component, you can export the type as well.

export type AppleProps = {}
export class Apple extends React.Component<AppleProps> {
}

You can then use them as:

import { Apple, AppleProps } from 'icons'

2 Comments

Does it means that I can't access exported props using Apple.Props and forced to make aliases in the root file for all the icons?
Apple.Props does not exist. Unless you explicitly set it, the ideal approach to access the props would be ComponentProps<typeof Apple> as @98sean98 suggested.

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.