hopeless-programmer
hopeless-programmer

Reputation: 990

Nested export in typescript

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}/>
  }
}

Upvotes: 2

Views: 806

Answers (2)

juliomalves
juliomalves

Reputation: 50278

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'

Upvotes: 1

98sean98
98sean98

Reputation: 352

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.

Upvotes: 2

Related Questions