0

I get a tslint error when I use any to pass the state in my React application written in typescript to a function.

no-any: Type declaration of 'any' loses type-safety. Consider replacing it with a more precise type.

class AssetDrillDown extends React.Component<{}, IDetailsListAssetsState> {

constructor(props: {}) {
  super(props);

  this.state = {
    items: _items
  };
}

public componentDidMount(): void {
    this.getData(this);
}

public getData(that: any): void {
    // not relevant code
    that.setState({items: _items});
}
}

I would like to not use any, and use a type to fix this issue. How can I do that, please guide.

0

2 Answers 2

1

You have already specified that the state of the react component is IDetailsListAssetsState.

Thus, if you are passing state in the function, you can do this:

public getData(that: IDetailsListAssetsState): void {
  // now you can read `that.items`
  ...
}

However, your code for the getData suggests you are passing down the AssetDrillDown instance instead of the state if you want to do that.setState({items: _items});

then you'd do something link this:

public getData(that: AssetDrillDown): void {
  // now you can read that.state.items
  ...
}

NOTE: Although there might be a reason for your code example, there is no need to pass down the instance of the class into the same class method. You can simply access the state like this.

public getData(): void {
  this.state.items
}
Sign up to request clarification or add additional context in comments.

Comments

0

You should define the state as an interface, in which you can define in a type safe manner what you class expects, explained quite well here.

The props interface is the first argument inside the generics diamond operator, and the state the second.

interface IHelloFormProps {
    name: string;
    handleChange(event: any): void;
}
interface IHelloFormState {
    inputName: string;
}
...
export default class HelloForm extends React.Component<IHelloFormProps, IHelloFormState> {
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.