styke
styke

Reputation: 2174

Typescript/React - destructuring from this.state throws error

I have the following method in one of my React components:

getRandomColor(){
  const { colors }: { colors: any } = this.state;
  return colors[Math.floor(Math.random() * colors.length)];
}

However, typescript is throwing me an error at the destructuring statement, and I have no idea why:

Type 'Readonly<{}>' is not assignable to type '{ colors: any; }'. Property 'colors' is missing in type 'Readonly<{}>'.

Can someone tell me why? I definitely set this.state.colors in the constructor and even if I didn't, I'm not entirely sure why it would throw me that error.

Upvotes: 2

Views: 2210

Answers (2)

styke
styke

Reputation: 2174

In TypeScript, class properties need type definitions:

https://www.typescriptlang.org/docs/handbook/classes.html

this.state being a property of my component class also needed that type definition:

interface State{
  colors: string[];
};

class ColorPicker extends React.Component {
  state: State;
  //...
}

After I added this, the error went away.

Upvotes: 1

jmargolisvt
jmargolisvt

Reputation: 6088

The correct syntax for destructuring is like this:

const { colors } = this.state;

This assumes there is a this.state.colors

Upvotes: 0

Related Questions