Search code examples
reactjstypescriptreact-proptypes

React typescript, Property 'propTypes' does not exist on type 'typeof TodoFilterItem'. TS2339


I have an interface

interface ITodoFilterItem  {
  name: string,
  filter: string,
  filterTodos: any
}

and a class in the same file that references it

class TodoFilterItem extends Component<ITodoFilterItem> {
  constructor (props:ITodoFilterItem) {
    super(props);
    this.handleFilter = this.handleFilter.bind(this);
  }

but when I try and add propTypes at the bottom of this file with

TodoFilterItem.propTypes = {
  name: PropTypes.string,
  filter: PropTypes.string,
  filterTodos: PropTypes.any
}

I get:


Property 'propTypes' does not exist on type 'typeof TodoFilterItem'.  TS2339

fyi: I have import PropTypes from 'prop-types'; at the top


Solution

  • TS requires that all static properties are initialized in the class definition. Add the following to your class to ensure TS can analyze the class properly.

    static propTypes: {
       name: Requireable<string>;
       filter: Requireable<string>;
       filterTodos: Requireable<any>;
    };
    
    import React, { Component, Requireable } from 'react';
    import PropTypes from 'prop-types';
    
    interface ITodoFilterItem {
        name: string;
        filter: string;
        filterTodos: any;
    }
    
    class TodoFilterItem extends Component<ITodoFilterItem> {
        static propTypes: {
            name: Requireable<string>;
            filter: Requireable<string>;
            filterTodos: Requireable<any>;
        };
    
        constructor(props: ITodoFilterItem) {
            super(props);
            this.handleFilter = this.handleFilter.bind(this);
        }
    
        handleFilter() {}
    
        render() {
            return <span />;
        }
    }
    
    TodoFilterItem.propTypes = {
        name: PropTypes.string,
        filter: PropTypes.string,
        filterTodos: PropTypes.any,
    };
    
    export default TodoFilterItem;