Typescript: 支持ES6类的构造函数属性

创建于 2016-03-21  ·  3评论  ·  资料来源: microsoft/TypeScript

TypeScript版本:

1.7.5

class Foo extends React.Component<any, any> {
 // ... some class definitions
}
Foo.defaultProps = {
  bar: 'baz'
}

预期行为:

没错

实际行为:

TS2339:类型“ typeof Foo”上不存在属性“ defaultProps”。

描述

嗨,我想使用带有ES6类的typescript创建react

如果我可以像上面那样设置类属性而不是类主体,那将是很棒的。 似乎打字稿不支持它?

Question

最有用的评论

错误是默认情况下Foo没有defaultProps静态属性。 因此,您只需要告诉编译器您想要这样的属性。

class Foo extends React.Component<any, any> {
    static defaultProps: any;
}

Foo.defaultProps = {
  bar: 'baz'
}

通常,如果道具的类型P而不是any ,则道具将为class Foo extends React.Component<P, ...static defaultProps: P;

所有3条评论

错误是默认情况下Foo没有defaultProps静态属性。 因此,您只需要告诉编译器您想要这样的属性。

class Foo extends React.Component<any, any> {
    static defaultProps: any;
}

Foo.defaultProps = {
  bar: 'baz'
}

通常,如果道具的类型P而不是any ,则道具将为class Foo extends React.Component<P, ...static defaultProps: P;

您也可以使用模块合并来减少一些代码:

class Foo { ... }
namespace Foo {
  export const defaultProps = {
    ...
  }
}

非常感谢您的友好回答! :+1:

此页面是否有帮助?
0 / 5 - 0 等级