Sat Jan 21 2023

Property “x” does not exist on union type in typescript when object destructuring

An outline into how to destructure object properties when coming across the "Property “x” does not exist on union type" warning"

Recently I came across a typescript warning when I was trying to destructure a few properties from the props that were being passed into a component. A simplified version of the code looked like this

Screenshot 2023-01-21 at 16.12.27

Okay, the warning is pretty explicit and I thought it would be a straightforward fix using the “in” operator provided by TypeScript. 

The documentation gives a pretty nice definition of this operator

JavaScript has an operator for determining if an object has a property with a name: the in operator. TypeScript takes this into account as a way to narrow down potential types.

So I narrowed the types

1import React from "react";
2interface One {
3 location: {
4 search: string,
5 hash: string,
6 asPath: string,
7 };
8}
9interface Two {
10 location: {
11 search: string,
12 hash: string,
13 };
14}
15const index = ({ location }: One | Two) => {
16 if ("asPath" in location) {
17 const { asPath } = location;
18 }
19 console.log(asPath);
20 return <div>Some Component</div>;
21};
22export default index;
23

The only problem here was that I couldn't access the destructured asPath property as it was not within the scope.

Here’s what I eventually did to destructure and then access the properties of my location data object

1import React from "react";
2interface One {
3 location: {
4 search: string,
5 hash: string,
6 asPath: string,
7 };
8}
9interface Two {
10 location: {
11 search: string,
12 hash: string,
13 };
14}
15const index = ({ location }: One | Two) => {
16 let asPath;
17 let hash;
18 let search;
19 if ("asPath" in location) {
20 ({ asPath, hash, search } = location);
21 } else {
22 ({ hash, search } = location);
23 }
24 console.log(asPath, hash, search);
25 return <div>Some Component</div>;
26};
27export default index;

Hope this helps if you encounter such an issue in the future! Let me know if the above helped!

Till next time!

Comments