Tips for accessing the data type of a nested property in TypeScript

If I want to keep the following declarations as they are, how can I specifically retrieve the type of the members property?

export type Members = {
  __typename?: 'Members';
  id?: Maybe<Scalars['String']>;
  ...
};

export type ProjectQuery = {
  __typename?: 'Query';
  Project?:
    | {
        __typename?: 'Project';
        teams?:
          | Array<
              | {
                  __typename?: 'Teams';
                  members?:
                    | Array<
                        | {
                            __typename?: 'Members';
                            id?: string | null | undefined;
                            ...
                          }
                        | null
                        | undefined
                      >
                    | null
                    | undefined;
                }
              | null
              | undefined
            >
          | null
          | undefined;
      }
    | null
    | undefined;
};

export type ProjectData = NonNullable<ProjectQuery['Project']>;

In my Vue store, I attempted this:

async myStoreAction(context, { Members }: { members: NonNullable<ProjectData['teams']['members']> }) { ... }

Answer №1

NonNullable is utilized on the final outcome of any type parameter it receives, requiring each nullable property to be wrapped with it. For example,

NonNullable<NonNullable<ProjectQuery['Project']>['teams']>
. Moreover, using & {} eliminates null and undefined values, which can lead to slightly more readable code:

type ProjectData = ProjectQuery['Project'] & {};
type Members = ((ProjectData['teams'] & {})[number] & {})['members'];
async myStoreAction(context, { members }: { members: Members }) { ... }

No matter what you do, the code may appear unappealing. If you desire a utility that ensures your type and all its descendants are non-nullable, consider checking out this alternative Stack Overflow post.

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

Deactivating Bootstrap Modal in Angular

Looking for advice on managing a Bootstrap Modal in Angular 7 I have a Form inside a Bootstrap Modal that I need to reset when the modal is closed (by clicking outside of it). Despite searching on Google, I haven't been able to find a solution. Any ...

Is the return type determined by the parameter type?

I need to create an interface that can handle different types of parameters from a third-party library, which will determine the return type. The return types could also be complex types or basic types like void or null. Here is a simple example demonstra ...

What is the best way for a Vue component to update a list in a different component that it's not directly related to?

There are two main components in my project: <filter-controls></filter-controls> <data-list></data-list> The <data-list> component contains a list of items, such as ingredients, that can be filtered based on user input. Me ...

Can you explain the distinction between @types/material-ui and the official @mui/types bundle?

When it comes to npm packages, I came across @types/material-ui and @mui/types. I'm aware that the former is backed by the Definitely Typed community, but what's the reasoning behind its existence when an official types package already exists? D ...

Using inline SVG in a Vite production build

When utilizing Vite and Vue, my goal is to compile a single JavaScript file without creating an assets directory that includes SVG and GIF files during the build process. I want to achieve this without manually inserting the SVG code in a Vue JS file as a ...

Angular: Understanding the intricacies of HTTP calls in ngOnInit versus click events (potentially related to caching mechanisms)

Within my Angular application, I have a basic service configured to communicate with the server. The service has been injected into a component. Interestingly, when I directly call one of its methods inside the ngOnInit() method of the component, everythin ...

Creating an array of reusable components in Vue 3 with Typescript - How can I pass it into another component?

I have developed a customizable Button component that can be styled dynamically and accept values for text/icons, etc. Here is the code for my "ActionButton" in Vue 3. Although I am new to this framework, I am facing some difficulties understanding certai ...

Difficulty persisting when removing accents/diacritics from a string in Angular with IE 11

When attempting to utilize the String.normalize("NFD").replace(/[\u0300-\u036f]/g, "") method, I encountered an issue in IE11. ERROR TypeError: The object does not support the property or method "normalize" ...

What are some ways to conceal the v-btn component?

btn : false <v-btn value="false">1</v-btn> <v-btn v-model="btn">2</v-btn> I need to conceal the v-btn component. However, both v-btn 1 and 2 remain visible. Is there a solution for this issue? Thank you. ...

"Unlocking the treasure trove: Extracting a single item from my Firebase real-time database using

Searching for the user's article in my Realtime database to display information. https://i.sstatic.net/yCdgf.png This is my Ionic script page Below are the imports I have: I am able to retrieve the user's ID, but I'm facing difficulty in ...

Typescript subtraction operation may result in Undefined

I am a beginner in the world of TypeScript and I'm currently struggling with running this code snippet: class TestClass { public t: number = 10; constructor() { this.t = this.t - 1; console.log(this.t); } } var obj = new TestClass(); ...

Angular dependency issue: Expected '{' or ';' for @types/node

I encountered an error while running "ng serve" in my Angular application. Originally built as Angular 2, it was upgraded to Angular 8 (with attempts at versions 6 and 7 along the way). However, after migrating from Angular 5, I started experiencing errors ...

Using Material UI date picker with TypeScript: A Complete Guide

Well, I have to admit that I usually don't resort to putting 'any' as the type when I'm uncertain what to do, but right now, I'm starting to feel quite frustrated. I'm currently working with Material UI date picker in conjunct ...

When someone visits a site using Next.js, the redirect feature may successfully load the site, but it fails to actually

I have a serverless logout function in Next.js: import magic from './magic'; import { withSessionRoute } from './sessions'; export default withSessionRoute(async function logoutHandler( request, response, ) { try { if (reques ...

Event handling for Vuetify's rating component - click

I'm currently utilizing Vuetify's v-rating component to display the average rating based on the v-model. An issue arises when a user tries to update the rating by clicking on the component, as there is no event emitted when the current rating mat ...

Steps to accessing parent component methods from child component in Vue.js

In my child component, I have a click event that I want to use to call a function or method in the parent component. Here is the code for the click event: <button @click.native="addNew" /> And here is the method in the child component: met ...

What is the correct way to destructure a tuple in Typescript when only certain values will be assigned to new variables?

When writing code, I frequently encounter situations that resemble the following: function example(parameter: string) { const tuple = [ "newParameterValue", "newVariableValue" ] let newVar; [parameter, newVar] = tuple; } ( ...

transform an array encoded in base64 format into a JSON object

I am encountering an issue where the base64 array I'm trying to send to an API is coming up empty. Here's a breakdown of what I'm doing: Firstly, I have an array of files with images in my code: [0: File {name: '766_generated.jpg' ...

Is there a way to incorporate a loading spinner into a MaterialUI DataTable without having to specify a fixed height for the parent component?

Currently, I am using a MaterialUI DataTable with the following setup: <div style = {{height: 300}}> <DataGrid loading={true} getRowHeight={() => "auto"} getEstimatedRowHeight={() => 250} ...

What is the best way to delete the "Click to sort Ascending" text from the header of each column in a bootstrap-vue table?

Recently, I came across a bootstrap-vue table that caught my attention: Below is the code snippet for the table setup: <template> <div class="container"> <h1 class="pt-2 pb-3">Bootstrap Table</h1> ...