4
votes

I want to use an ES6 React component in another Typescript component.

The ES6 component:

class ModelViewer extends Component {
  constructor(props, context) {
    super(props, context);
    //...
  }
// ...
}
export default ModelViewer;

My consuming TS component:

import * as ReactDOM from "react-dom";
import * as React from "react";
import ModelViewer from "./model_viewer/ModelViewer";

export class Viewer extends React.Component<any, any> {
    render() {
        return (
                <div>
                    <ModelViewer />
                </div>
        );
    }
}

Options for the TSC are:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "removeComments": true,
        "sourceMap": true,
        "allowJs": true,
        "watch": true,
        "outDir": "./dist/",
        "jsx": "react",
        "experimentalDecorators": true,
        "allowSyntheticDefaultImports": true
    }
}

Now I'm receiving the error TS2605: JSX element type 'ModelViewer' is not a constructor function for JSX elements.

Do I need to provide typings despite having set "allowJS": true? I've tried different ways to import, but no difference.

1
The full error is App.tsx(11,17): error TS2605: JSX element type 'ModelViewer' is not a constructor function for JSX elements. Property 'setState' is missing in type 'ModelViewer'. I think TSC doesn't understand extends Component... try import {Component} from "react" in your ES6 component.Aaron Beall
also I noticed you are missing 'React.Component' on your model viewer class. Aside from that, as long as the import path is correct you shouldn't be receiving any more errors relating to "not a constructor."Matt Fernandez
Have you found a solution for this problem? I have the same issuetcoopman

1 Answers

3
votes

As a kind of brute force method I satisfied the Typescript compiler using a custom typings file.

// typings/custom.d.ts
declare module "*";

And tell the compiler in my tsconfig.json to read my custom typings:

// tsconfig.json
{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "removeComments": true,
        "sourceMap": true,
        "allowJs": true,
        "watch": true,
        "outDir": "./dist/",
        "jsx": "react",
        "experimentalDecorators": true,
        "allowSyntheticDefaultImports": true,
        "typeRoots": [
             "./typings",
             "node_modules/@types"
         ]
    }
}