Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct syntax for React.createElement in TypeScript/JSX

I cannot get React.createElement to compile in TypeScript.

interface IColorPickerProps {

}

interface IColorPickerState {

}

class ColorPicker extends React.Component<IColorPickerProps, IColorPickerState> { 
    constructor(props: IColorPickerProps) {
        super(props);
    }
}

Component creation:

let props: any = {}
React.createElement(ColorPicker, props)

I get this compile error:

Argument of type 'typeof ColorPicker' is not assignable to parameter of type 'string | ComponentClass<IColorPickerProps> | StatelessComponent<IColorPickerProps>'.
  Type 'typeof ColorPicker' is not assignable to type 'StatelessComponent<IColorPickerProps>'.
    Type 'typeof ColorPicker' provides no match for the signature '(props: IColorPickerProps & { children?: ReactNode; }, context?: any): ReactElement<any> | null'.

If I remove the constructor, the error goes away. I cannot use the syntax as props needs to be passed dynamically. Any ideas?

like image 237
olivierr91 Avatar asked Feb 02 '26 02:02

olivierr91


1 Answers

The code you have compiles fine for me when I run filename.tsx, then node filename.js. Is There other code that you have along with this?

The whole point of typing the props in the class, is so you know what will be passed to your ColorPicker class. In my opinion, the best thing to do would be to fix your IColorPickerProps interface to include the props that will be passed like this.

interface IColorPickerProps {
    name: string,
    age: number
}

And then

let myprops: IColorPickerProps = {
    name: ...
    age: ...
}

If you are typing your props as any, then you're sort of defeating the purpose of type-checking.

like image 81
becks Avatar answered Feb 03 '26 20:02

becks