When defining react components using typescript we can write something like:
class SomeComponent extends React.Component {
This works, though it may not be so good.
// Foo.jsx
import * as React from 'react';
/**
* @type {{ new(props: any): {
props: { a: string, b: number },
state: any,
context: any,
refs: any,
render: any,
setState: any,
forceUpdate: any
} }}
*/
const Foo = class Foo extends React.Component {
render() {
return <div className={this.props.a}>{this.props.b}</div>;
}
};
export default Foo;
// import Foo and use it in .tsx or .jsx file
import Foo from './Foo';
<Foo/>; // error: Type '{}' is not assignable to type '{ a: string; b: number; }'
<Foo a='a' b={0}/>; // OK
In case someone is searching for an alternate solution. Regarding to this Typescript issue you can also achieve it like this.
import React, { Component } from 'react';
import PropTypes from 'prop-types';
/**
* @augments {Component<{onSubmit:function, text:string}>}
* @param {object} event - Input event
* @return {React.ReactElement} - React component
*/
class Test extends Component {
handleInput = (event) => {
event.preventDefault();
this.props.onSubmit(event.target.value);
};
render() {
const { text } = this.props;
return <div>Hello, property :O {text}</div>;
}
}
Test.propTypes = {
onSubmit: PropTypes.func.isRequired,
text: PropTypes.string.isRequired,
};
export default Test;
I prefer following form (es2015 + @types/react):
/**
* @typedef {object} Props
* @prop {string} className
* @prop {number} numberProp
*
* @extends {Component<Props>}
*/
export default class SomeComponent extends Component {
render() {
return (
<div className={this.props.className}>
{this.props.numberProp}
</div>
);
}
}