简体   繁体   中英

Typescript/React: Module has no exported member

I am trying to export prop types from one view component to another container component and use them as state type definitions:

// ./Component.tsx
export type Props {
    someProp: string;
}

export const Component = (props: Props ) => {
    ...etc
}

// ./AnotherComponent.tsx
import { Component, Props as ComponentProps } from "./Component";

type Props = {}

type State = ComponentProps & {};

class AnotherComponent extends React.Component<Props, State> {
    state: State;
    ...etc
}

However I am getting in console:

Module '"./Component "' has no exported member 'Props'.

Any suggestions for how I should be going about this?

I have also tried using lookup types as per this article, but no joy.

Try something like this. Basically extend the component Props, to include your desired import.

export interface IProps extends PropsOfYouChoiceThatYouImport {
 morePropsHere
}

Also do not include Props into State it is completly wrong IMO. Do something like this:


interface IProps extends YourDesiredProps {
  someProp: string | null;
  // etc
}

interface IState {
  something: boolean
  // etc
}

export class ComponentName extends Component<IProps, IState> {
  // Define you state, and props here. You need to initialize the correct IState 
  // and IProps above
}

As for the console error, I am not sure you can do that.Try create a folder called Types or Interfaces . Then export that one.

And import it as named or default export, whatever you wish, at both files. Since you want to reuse it. Tell me if it helps. I can look more into it, if you make a quick codeSandbox..

Basically what I suggest is put this into a separate file:

export type Props {
    someProp: string;
}

If you check the React typings ( node_modules/react/index.d.ts ) of React.Component the structure is the following:

class Component<P, S> {...}

where P equal props and S means state. You should not mix props and state.

To fix your TypeScript error change type to interface :

export interface Props {
  someProp: string;
}

The issue for the missing member export was the fact that I had an intermediary index file which TypeScript doesn't seem to be able to use when exporting types:

// ./Component/index.tsx
export { Component, Props } from "./js/Component";

When I change the import to use an exact path to the file rather than trying to import it through the index file it picked it up:

// ./AnotherComponent/js/AnotherComponent.tsx
import { Props as ComponentProps} from "./Component/js/Component";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM