类型上不存在属性“defaultProps”

Coo*_*oop 5 javascript typescript reactjs eslint

我有一个 Typescript React 类组件,如下所示:

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;
Run Code Online (Sandbox Code Playgroud)

在这里,我收到以下类型错误:

Property 'defaultProps' does not exist on type 'typeof Foo'.
Run Code Online (Sandbox Code Playgroud)

我看到 2 个解决方案来解决这个问题。一种是在类上声明类型,如下所示:

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

  render() {
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

另一种是在类中完全像这样声明 defaultProps :

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

  render() {
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用 eslint-config-airbnb 18.0.1 和 eslint 6.1.0 所以这两个解决方案都会抛出这个 eslint 错误:

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

有没有办法在类外声明 defaultProps 而不抛出类型错误?

ano*_*666 5

TS 文档说静态 defaultProps 是要走的路

在 TS 之上添加 eslint 似乎很奇怪,我相信 airbnb 配置适用于 javascript,而不是 TypeScript。

  • Typescript 检查类型,而 ESLint 检查各种格式和其他内容(例如与 Prettier 的集成)。Typescript 似乎也放弃了对 TSLint 的支持,并建议现在使用 ESLint。Airbnb 配置是 React 的行业标准,因此我不想放弃行业标准规则,因为我使用的是 Typescript 而不是 JavaScript。除了这 1 条规则之外,它适用于我的整个应用程序。 (2认同)