gpt4 book ai didi

javascript - 类型上不存在属性 'defaultProps'

转载 作者:行者123 更新时间:2023-11-30 13:54:57 25 4
gpt4 key购买 nike

我有一个像这样的 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' 应该在类主体之外声明(react/static-property-placement)

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

最佳答案

TS 文档说静态 defaultProps 是 the way to go .

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

关于javascript - 类型上不存在属性 'defaultProps',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57490998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com