Retrieving the property of a union type comprising a void type and an unnamed type

Currently, I am working on a project involving GraphQL. In my code, I have encountered a GraphQLError object with a property named extensions. The type of this property is either void or { [key: string]: any; }. Whenever I try to access any property within extensions, an error occurs:

x.extensions.code === 'UNAUTHENTICATED'


Property 'code' does not exist on type 'void | { [key: string]: any; }'.
  Property 'code' does not exist on type 'void'.

To resolve the issue of accessing properties that do not exist in a union type, a potential solution can be found here: https://github.com/Microsoft/TypeScript/issues/12815#issuecomment-266193707

let pet = getSmallPet();

if ((<Fish>pet).swim) {
    (<Fish>pet).swim();
}
else {
    (<Bird>pet).fly();
}

However, the challenge lies in performing a type assertion without a specific type name.

If you have any insights on how I can address this dilemma, I would greatly appreciate it.

Best regards, Richard

Answer №1

One way to narrow down the type of a union in TypeScript is by using type guards:

declare let obj: {
    extensions: void | { [key: string]: any; }
}

obj.extensions["test"] // this will cause an error
if (obj.extensions) {
    obj.extensions["test"] // this is fine now
}

Note: Make sure to have strictNullChecks enabled in order for errors to be thrown in your code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to determine if a tuple is of infinite or finite length?

Is there a way to determine if a tuple is finite or infinite? I've been working on a solution, but it doesn't cover all cases: type IsFinite<T extends any[], Finite = true, Infinite = false> = T extends [] ? Finite : T extends (infer E ...

Reattempting a Promise in Typescript when encountering an error

I am currently working on a nodeJS application that utilizes the mssql driver to communicate with my SQL database. My goal is to have a unified function for retrieving a value from the database. However, in the scenario where the table does not exist upon ...

It appears that Type 'MenuItemsProps' does not contain a property named 'map'. This might be causing the error message 'Property 'map' does not exist on

Recently, I delved into learning TypeScript and decided to convert my React code into TypeScript. However, I encountered an issue that left me stumped. I tried passing a state through props to a component with a defined value, hoping that the state would b ...

How to Install Definitely Typed Packages in Visual Studio 2015 RC for AspNet5 with the Help of Gulp and TSD

Struggling to add angular.d.ts to my MVC6 project, I've hit a roadblock. Although I've configured Gulp to reinstall necessary packages using tsd, I'm stuck on the initial installation process. The instructions suggest running 'tsd inst ...

Distribute your SolidJS Typescript components on npm

Recently, I developed a SolidJS TypeScript UI component and successfully published it to the npm registry. The project structure is organized as follows: |-app |-index.html |-src |-index.tsx |-App.tsx |-utils |- ... |-com ...

Is there an array containing unique DateTime strings?

I am dealing with an Array<object> containing n objects of a specific type. { name: 'random', startDate: '2017-11-10 09:00', endDate: '2017-11-23 11:00' } My goal is to filter this array before rendering the resu ...

What could be causing the vue-property-decorator @Emit to malfunction in my Vue TypeScript file?

I am currently working with Typescript and Vuejs, where I have a child component called child.component.tsx import Vue from 'vue'; import Component from 'vue-class-component'; import { Emit } from 'vue-property-decorator'; ...

Is there a way to determine the quantity of lines within a div using a Vue3 watcher?

Is it feasible to determine the number of text lines in a div without line breaks? I am looking to dynamically display or hide my CTA link based on whether the text is less than or equal to the -webkit-line-clamp value: SCRIPT: const isExpanded = ref(true ...

Is it possible to verify type equality in Typescript?

If the types do not match, I want to receive an error. Here is an example of an object: const ACTIVITY_ATTRIBUTES = { onsite: { id: "applied", .... }, online: { id: "applied_online", .... }, ... } as co ...

What causes the duplication of my data when using server-side data fetching with Next.js and @apollo/client?

I am currently working on a project using nextjs and @apollo/client. The data for my project is fetched from an external API. However, I have encountered an issue where when I navigate to a different page and then go back to the previous page, the data is ...

Key factors to keep in mind when comparing JavaScript dates: months

Check the dates and determine if the enddate refers to the following month by returning a boolean value. Example startdate = January 15, 2020 enddate = February 02, 2020 Output : enddate is a future month startdate = January 15, 2020 enddate = January 2 ...

Using TypeScript, creating a tagged template literal for running Jest tests with the `test.each`

Struggling to construct a jest test.each with a tagged template literal test.each` height | text ${10} | ${undefined} ${20} | ${undefined} ${10} | ${'text'} ${20} | ${'text'} `('$height and $text behave as expected&a ...

retrieve asynchronous data from the server using ngrx

How can I retrieve asynchronous data from the server? I am looking to save this data in a global store for future updates. I'm having trouble grasping the concept of asynchronous calls, such as in Redux. While I was able to understand it with simpl ...

When a property is removed from a variable in an Angular Component, it can impact another variable

During the iteration of the results property, I am assigning its value to another property called moreResults. After this assignment, I proceed to remove array elements from the testDetails within the moreResults property. However, it seems that the remova ...

Utilizing Angular 2 alongside ngrx/store for seamless updates to specific properties within the state object without disrupting the entire structure

I am facing an issue where I need to update a property of a state object without creating a new object. Is there a way to add or update a single property without replacing the entire object? Below is the reducer code: const initialState = { all: [], ...

Please ensure the subscription has completed before proceeding with the loop

I am currently working on an Angular application that retrieves data from an API and uses one of its parameters from a looped array. The issue I'm facing is that the data is pushed in a random order due to the continuous looping without waiting for th ...

I encountered an error stating "Buffer is not defined" originating from the Deode/Encode Stream Bundle.js script, not from my own code

I've encountered a major issue while attempting to update my npm project to webpack 5, and now I'm left with just one persistent error: bundle.js:1088566 Uncaught ReferenceError: Buffer is not defined at bundle.js:1044980:24 ...

Tips for organizing MUI Card effectively within a React application using TypeScript

Struggling to build a React card component with Material-UI (MUI) and TypeScript that represents a car? The card should contain text, an image, checkboxes, a rating, and a button. Here's the code I've come up with so far: import React from ' ...

Making a HTTP Get request for a single item in Ionic 2

I have successfully implemented an API to retrieve data and display it on the page. It works perfectly for a json response containing more than one object, as it follows a "matches" hierarchy. However, I am facing an issue when trying to print out data for ...

How can I clear the cache for GetStaticPaths in NextJs and remove a dynamic route?

This question may seem basic, but I can't seem to find the answer anywhere online. Currently, I am diving into NextJs (using TypeScript) and I have successfully set up a site with dynamic routes, SSR, and incremental regeneration deployed on Vercel. ...