npm package @types/react
allows us to use React inside of our TypeScript apps.
We define components as
type Props = {...}
type State = {...}
export default class MyComponent extends React.Component<Props, State> {
}
here we have to declare types for component props and state (in type variables).
After we declared that types, TypeScript uses that to validate the usage of our component (the shape of props passed to it).
I want to create a container around such a component. The container will reuse the props of the component. But in order to create another component with the same props I have to redeclare the types for props again. Or export them from the original component file and import into container:
// original file
export type Props = {...}
// container file
import MyComponent, { Props } from './original'
But I'm already importing the MyComponent
from that file. This component already contains information about the props it consumes (thanks to type variables in React.Component
).
The question is how do I access that information from the component class itself without explicitly exporting/importing the type for props?
I want something like:
import MyComponent from './MyComponent'
type Props = MyComponent.Props // <= here access the component prop types
export default class MyContainer extends React.Component<Props, {}> {}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…