CaribouCode
CaribouCode

Reputation: 14398

Property 'defaultProps' does not exist on type

I have a Typescript React class component like so:

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;

Here I get the following type error:

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

I see 2 solutions to solve this. One is to declare the type on the class like so:

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

  render() {
    ...
  }
}

The other is to declare the defaultProps inside the class entirely like so:

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

  render() {
    ...
  }
}

I'm using eslint-config-airbnb 18.0.1 and eslint 6.1.0 so both of these solutions throw this eslint error:

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

Is there a way to declare defaultProps outside the class without throwing a type error?

Upvotes: 9

Views: 12753

Answers (2)

TOPKAT
TOPKAT

Reputation: 8648

your solution 2 is the best way to handle that case:


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

  render() {
    ...
  }
}

If you have the opportunity, the best and cleaner IMO would be to refactor your component to functional style:

function Foo({ 
  var1 = 'defaultValue, 
  var2 = 'default2 
}: Props) {
  return <View>...</View>
}

Upvotes: 0

TS docs say static defaultProps is the way to go.

Seems weird to add eslint on top of TS, I believe airbnb config is for javascript, not TypeScript.

Upvotes: 5

Related Questions