简体   繁体   中英

How to use typescript jsdoc annotations for React PropTypes

When defining react components using typescript we can write something like:

class SomeComponent extends React.Component<PropInterface, StateInterface> {
  // ...
}

Is there a way do the equivalent using jsdoc annotations and have props type-checked.

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>
        );
    }

}

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;

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

If you use PropTypes,

something like this works for me:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

/**
 * Test component
 * @augments {Component<Props, State>}
 */
class Test extends React.Component {
  // ...
}

Test.propTypes = {
  title: PropTypes.string.isRequired,
}

export default class Test1 extends React.Component {
  render() {
    return <Test  />
  }
}

vscode 属性类型智能感知

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