How to use typescript jsdoc annotations for React PropTypes

后端 未结 3 727
悲&欢浪女
悲&欢浪女 2021-02-07 14:22

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

class SomeComponent extends React.Component {
         


        
相关标签:
3条回答
  • 2021-02-07 15:02

    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
    
    0 讨论(0)
  • 2021-02-07 15:09

    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;
    
    0 讨论(0)
  • 2021-02-07 15:20

    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>
            );
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题