简体   繁体   中英

Property 'defaultProps' does not exist on type

I have a Typescript React class component like so:

import React, { Component } from 'react';

interface Props {
  bar?: boolean;
}

const defaultProps: Partial<Props> = {
  bar: false,
};

class Foo extends Component<Props> {
  render() {
    ...
  }
}

Foo.defaultProps = defaultProps;

export default Foo;

Here I get the following type error:

Property 'defaultProps' does not exist on type 'typeof Foo'.

I see 2 solutions to solve this. One is to declare the type on the class like so:

class Foo extends Component<Props> {
  static defaultProps: Partial<Props>;

  render() {
    ...
  }
}

The other is to declare the defaultProps inside the class entirely like so:

class Foo extends Component<Props> {
  static defaultProps: Partial<Props> = {
    bar: false,
  };

  render() {
    ...
  }
}

I'm using eslint-config-airbnb 18.0.1 and eslint 6.1.0 so both of these solutions throw this eslint error:

'defaultProps' should be declared outside the class body (react/static-property-placement)

Is there a way to declare defaultProps outside the class without throwing a type error?

TS docs say static defaultProps is the way to go .

Seems weird to add eslint on top of TS, I believe airbnb config is for javascript, not TypeScript.

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