kyun
kyun

Reputation: 10264

typescript optional chaining with object destructuring

I've just updated typescript to 3.7.4 and I am trying to edit my code.

I have a simple code

interface Test
  event: {
    queryStringParameters: { [name: string]: string } | null;
  }
}
const test:Test = (event) => {
  // const { no } = event?.queryStringParameters; //Property 'no' does not exist on type '{ [name: string]: string; } | null'.ts(2339)
  const no = event?.queryStringParameters?.no; //It works but I want to use above that.
  ...
}

I want to use the optional chaining with destructuring.

Is it available feature now?

Upvotes: 3

Views: 4319

Answers (1)

Terry
Terry

Reputation: 66103

That is because queryStringParameters can be null, and the null object does not contain the property no. You will need to use a null coalescing operator for that:

const { no } = event?.queryStringParameters ?? { no: null };

Note that the ?? operator is currently only available via TypeScript 3.7+ is not yet a standard JS operator as of now. See related discussion on TypeScripts repo for more details: https://github.com/microsoft/TypeScript/issues/26578

Upvotes: 9

Related Questions