简体   繁体   中英

Error with passing parameter to Typescript generic class with React

I want to use React Components for build a library.

I have a Component abstract class (the mother class component) with ComponentProps:

import * as React from "react";

/**
 * Main components properties
 * */
export interface ComponentProps {
    ContainerId: string,
    Id: string,
    CssClass: Array<string>,
    Attributes: Map<String, String>,
    Events: Map<String, String>
}

/**
 * Main component class
 * */
export default abstract class Component<Props extends ComponentProps>
    extends React.Component<Props & ComponentProps, {}> {

}

And a TextBox class extends the Component abstract class, with TextBoxProps, extends ComponentProps:

import * as React from "react";
import Component, { ComponentProps } from "../Component";
import { useState } from 'react';

export interface TextBoxProps extends ComponentProps {
    /**
     * Value of textbox
     * */
    Value: string,
    /**
     * Placeholder of textbox
     * */
    PlaceHolder: string
}

export default class TextBox<Props extends TextBoxProps> extends Component<Props & TextBoxProps> {
    render() {
        const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
            console.log("New value : " + event.target.value);
        };

        return (
            <div id={this.props.Id + "_cnt"}>
                <input
                    defaultValue={this.props.Value}
                    placeholder={this.props.PlaceHolder}
                    onChange={handleChange} />
            </div>
        );
    }
}

When I try to use the TextBox component with TextBoxProps, it's work on Visual Studio, but on Visual Studio Code, I have this error:

Generic type 'TextBox' requires 1 type argument(s). ts(2314)

Visual Studio Code TextBox's error

Anyone have any idea what I'm doing wrong?

Edit: My current tsconfig

{
  "compilerOptions": {
    // Default
    "target": "es5",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,

    // Added
    "jsx": "react",
    "module": "ESNext",
    "declaration": true,
    "declarationDir": "types",
    "sourceMap": true,
    "outDir": "dist",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "emitDeclarationOnly": true
  }
}

I checked your code. There is a problem.

When you want to render something with react-dom, you should do it in.tsx file not.ts file.

Changing src/components/index.ts to src/components/index.tsx will fix your issue.

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