繁体   English   中英

类型不存在属性“ defaultProps”

[英]Property 'defaultProps' does not exist on type

我有一个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;

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

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

我看到2种解决方案来解决这个问题。 一种是像这样声明类的类型:

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

  render() {
    ...
  }
}

另一种方法是完全在类内部声明defaultProps,如下所示:

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

  render() {
    ...
  }
}

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

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

有没有一种方法可以在类外声明defaultProps而不会引发类型错误?

TS文档说静态defaultProps是可行的方法

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM