I am trying to create and compile an React Higer Order Component in Typescript.
But I get an error. Firstly VSCode complains about this
'WrappedComponent' refers to a value, but is being used as a type here.
** And my Typescript compiler throws this error.**
lib/auth.ts:44:30 - error TS1005: '>' expected.
44 return <WrappedComponent {...this.props} />;
~
lib/auth.ts:44:47 - error TS1109: Expression expected.
44 return <WrappedComponent {...this.props} />;
~
lib/auth.ts:44:48 - error TS1109: Expression expected.
44 return <WrappedComponent {...this.props} />;
**Here is my code below of the React HOC component **
import * as React from 'react';
import Router from 'next/router';
import { NextContext } from 'next';
import nextCookie from 'next-cookies';
import { MOVED_TEMPORARILY } from 'http-status-codes';
interface ComponentExtra extends React.Component, React.SFC {
getInitialProps: Function;
}
export const withAuthSync = (WrappedComponent: ComponentExtra) => class extends React.Component {
static async getInitialProps(ctx: NextContext) {
const token = auth(ctx);
const componentProps = WrappedComponent.getInitialProps && (await WrappedComponent.getInitialProps(ctx));
return { ...componentProps, token };
}
render() {
return <WrappedComponent {...this.props} />;
}
};
export const auth = (ctx: NextContext) => {
const { req, res } = ctx;
const { token } = nextCookie(ctx);
if (req && res && !token) {
res.writeHead(MOVED_TEMPORARILY, { Location: '/signin' }).end();
return;
}
return token;
};
**Update the error was due to the file extension was not .tsx but .ts **
Solution for VS Code Errors that comes when you install TypeScript version of React JS The error mostly because of the version of TypeScript selected by your VS Code IDE. Restarting the VS Code IDE sometimes fixes the problem, if not, we need to explicitly select the version of TypeScript from VS Code.
To solve the "Cannot find module react or its corresponding type declarations" error, install the module and its type definitions by running the commands npm install react and npm i --save-dev @types/react.
Use the type interface React.ComponentType to define the component parameter in your custom React HOC (higher order component).
It also passes the state value as a prop to the child component. Here’s how to use the React HOC. interface ContainerProps { areYouCool: boolean; } const Container: React.SFC<ContainerProps> = props => ( <h1> {props.areYouCool ?
The error means that JSX syntax isn't parsed as such:
lib/auth.ts:44:30 - error TS1005: '>' expected.
44 return <WrappedComponent {...this.props} />;
In order to do that, auth.ts should be renamed to auth.tsx. In case TypeScript was configured correctly for JSX, this the only fix that is need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With