cubsnlinux
cubsnlinux

Reputation: 385

Creating a Higher Order Component (HOC) with TypeScript

I am trying to define a higher order component using TypeScript and I am getting weird errors.

I have tried looking at react type definitions to understand the problem but with no success.

The code below is part of a react app generated with 'create-react-app' - 'create-react-app hoc --typescript'

import React from 'react';

const wrapper = (ChildComponent:React.ComponentType) => {

  const ComposedComponent:React.FC = ():JSX.Element => {

      return (
        // The line below results in the error - 'Type 'boolean' is not assignable to type 'Element'.ts(2322)'
        <div>Hello</div> 

      );
  };

  return ComposedComponent;

};

Here is my tsconfig.json -

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}

Here is the typescript error when I run the app -

Unterminated regular expression literal.  TS1161

    3 | const wrapper = (ChildComponent: React.ComponentType) => {
    4 |   const ComposedComponent: React.FC = (): JSX.Element => {
  > 5 |     return <div>Hello</div>;
      |                        ^
    6 |   };
    7 | 
    8 |   return ComposedComponent;

I don't understand why the JSX snippet is resolved to boolean by Typescript. What am I doing wrong here?

Upvotes: 0

Views: 870

Answers (1)

cubsnlinux
cubsnlinux

Reputation: 385

This was silly. It looks like to use JSX the file extension should 'tsx'. Mine was 'ts'. I changed the extension to 'tsx' and the error went away. Super frustrating.

Thanks everyone!

I haven't figured out how to pass a prop to the wrapper and ultimately to the ChildComponent

Upvotes: 3

Related Questions