Typescript: Support of ES6 class constructor property

Created on 21 Mar 2016  ·  3Comments  ·  Source: microsoft/TypeScript

TypeScript Version:

1.7.5

Code

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

Expected behavior:

No error.

Actual behavior:

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

Description

Hi, I'd like to create react class using typescript with ES6 classes, and encountered above error.

It would be awesome if I can set class property like above instead of class body. seems typescript does not supports it?

Question

Most helpful comment

The error is that by default there is no defaultProps static property on Foo. So you just have to tell the compiler that you want such a property.

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

Foo.defaultProps = {
  bar: 'baz'
}

In general, if the props was of some type P instead of any, then it would be class Foo extends React.Component<P, ... and static defaultProps: P;

All 3 comments

The error is that by default there is no defaultProps static property on Foo. So you just have to tell the compiler that you want such a property.

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

Foo.defaultProps = {
  bar: 'baz'
}

In general, if the props was of some type P instead of any, then it would be class Foo extends React.Component<P, ... and static defaultProps: P;

You can also use module merging for slightly less code:

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

Thank you very much for kind answers! :+1:

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zhuravlikjb picture zhuravlikjb  ·  3Comments

Roam-Cooper picture Roam-Cooper  ·  3Comments

Antony-Jones picture Antony-Jones  ·  3Comments

siddjain picture siddjain  ·  3Comments

jbondc picture jbondc  ·  3Comments