2

I want to define class in React with Typescript which has a method with html output. but get error about output type of function.

interface StateProps {
  page: string,
}
class App extends React.Component<StateProps,any> {
render() {
    return (
      <div className="App">
        {this.pageContent(this.props.page)}
      </div>
    );
}
pageContent = (page:string) => {
    switch (page) {
      case "newPage":
         return <NewPage />;

      case "otherPage":
         return <OtherPage />;

      default:
        break;
    }
  }
}

error was: Type 'void' is not assignable to type 'ReactNode'.

eslint suggest use DetailedHTMLProps<HtmlAttributes<HTMLDivElement>,HTMLDivElement> but it didnt work.

0

1 Answer 1

5

if you have @types/react in your package.json you should be able to do

pageContent = (page:string): ReactNode | null => { 
  ... 
}

You probable want to return null instead of breaking. Typescript doesn't like types with optional return.

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

5 Comments

this made new error: Cannot invoke an object which is possibly 'null' or 'undefined'.
Can you provide a stacktrace ?
Cannot invoke an expression whose type lacks a call signature. Type 'string | number | boolean | {} | ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | ReactNodeArray | ReactPortal' has no compatible call signatures. TS2349
That must be an error in another part of your code. Maybe where you use the App component, or in one of the child components.
you said true. make project again and problem solved. thanks

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.