olivierr91
olivierr91

Reputation: 1415

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?

Upvotes: 3

Views: 4366

Answers (2)

olivierr91
olivierr91

Reputation: 1415

I have solved the problem by upgrading to latest version of React and latest version of the type definitions, this was probably a problem with the type definitions I was using. Thank you all for your help

Upvotes: 0

becks
becks

Reputation: 11

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.

Upvotes: 1

Related Questions