3

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?

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

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.