Akusas
Akusas

Reputation: 529

Object is possibly undefined even with if statement

I've got a Typescript error TS2532: Object is possibly 'undefined'. I'm creating an SPA using Typescript, and on one of the pages, then you have the possibility of uploading a file. The backend is already written, so the file stored in state will be made into a binary code which the server side reads. The file setstate is set to undefined.

I've done a few searches, but the solutions don't seem to work for me. The first solution was to create an if statement:

if (this.state.uploadFile !== undefined) {
  const terms = this.state.uploadFile;
  // Logic
}

Whenever terms is used in the logic portion, then I get the error mentioned above.

The other solution is to tell the compiler that it is definetly defined:

const terms = this.state!.uploadFile;

This still throws the same error, and thought I might have placed the ! in the wrong place, but when I move it to const terms = this.state.termSheet!; then that causes a new error when calling terms.getAsBinary() I get the error Property 'getAsBinary' does not exist on type 'never'

Code in context:

// Imports

class SubmitIssue extends React.Component<StylesProps> {
  state = {
    alert: false,
    amount: '',
    uploadFile: undefined,
    verify: false,
  }

  handleAmountChange(e) {
    this.setState({ amount: e.target.value });
  }

  handleFileChange(e) {
    this.setState({ uploadFile: e.target.files[0] });
  }

  handleVerifyChange() {
    this.setState({ verify: !this.state.verify });
  }

  handleClick() {
    const config = { headers: { 'Content-Type': 'multipart/form-data' } };
    const bodyFormData = new FormData();
    bodyFormData.set('Amount', this.state.amount);
    bodyFormData.set('uploadFile', this.state.termSheet.getAsBinary());
    bodyFormData.set('Verify', this.state.verify.toString());

    axios.post(
      `${process.env.API_URL}RegisterIssue/Create`,
      bodyFormData,
      config
    ).then(res => {
      console.log(res);
      this.setState({ alert: true }, function() { this.sendData(); });
    }).catch((error) => {
      console.log(error);
    })
  }

  sendData() {
    const alertState = this.state.alert;
    this.props.parentAlertCallback(alertState);
  }  
  render() {
    return (
      // Design
    );
  }
}
export default withStyles(styles)(SubmitIssue);

So, I'm a little stumped as to what the correct way to handle this error is.

Upvotes: 1

Views: 3044

Answers (1)

brandt.codes
brandt.codes

Reputation: 923

It is because you check only state.uploadFile but use state.termSheet. There are two possible solutions:

You cat set a default value (in case terms is not defined):

const terms = this.state.termSheet ? this.state.termSheet : defaultValue;

Or you check the terms in the if statement, too:

if (this.state.uploadFile && this.state.termSheet)

Upvotes: 2

Related Questions