Tips for leveraging TypeScript's indexed access types when working with nullable nested types

Looking to create a TypeScript type based on another type.

This method is successful:

type Result = { data: { nestedData: { foo: string; bar: string } } };

type NestedData = Result['data']['nestedData'];

However, when the data property can be null, the following approach fails:

type Result = { data: { nestedData: { foo: string; bar: string } } | null };

type NestedData = Result['data']['nestedData'];

resulting in the error message:

Property 'nestedData' does not exist on type '{ nestedData: { foo: string; bar: string; }; } | null'.(2339)

Is there a way to define the NestedData type based on the Result type without repeating any part of the original typings?

Check out the demo on TypeScript Playground

Edit: I'm working with a tool generating my NestedData type and I'm defining NestedData as a concise type alias. The actual typing is more complex, so I aim to reduce redundancy.

Answer №1

To eliminate null (and undefined) from the union, you can utilize NonNullable:

type NestedData = NonNullable<Result['data']>['nestedData']

Playground Link

Alternatively, you can use Exclude in a more verbose manner:

type NestedData = Exclude<Result['data'], null>['nestedData']

Playground Link

Choosing one of these methods is logical when changing the Result type isn't an option. However, in other scenarios, defining them as follows might be more intuitive:

type NestedData = { foo: string; bar: string }
type Result = { data: { nestedData: NestedData } | null }

Answer №2

A simple method for accessing nullable properties:

type Result = {
    data: {
        nestedData: { foo: string; bar: string }
    } | null
};

type AccessNullable<T, Prop extends keyof NonNullable<T>> = NonNullable<T>[Prop]

type NestedInfo = AccessNullable<Result['data'], 'nestedData'>

View in Playground

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

Error Message: Angular Unit Test Fails with "Cannot read property 'subscribe' of undefined"In this article, we will

My Angular app's unit tests using Jest are giving me the error "TypeError: Cannot read property 'subscribe' of undefined". Despite searching online, none of the solutions provided seem to work for me. Below is some relevant code: page-view. ...

The command "ng test" threw an error due to an unexpected token 'const' being encountered

Any assistance with this matter would be greatly appreciated. I am in the process of constructing an Angular 5 project using angular/cli. The majority of the project has been built without any issues regarding the build or serve commands. However, when a ...

Sending data to a React component from regular HTML

I have a question about implementing a method to pass custom attributes from HTML elements as props to React components. Here's an example: function someFunction(props) { return <h1>props.something</h1> } HTML: <div id="someEl ...

Configuring global runtime variables in NextJS for server-side operations

Currently, I am utilizing the instrumentation.ts file in NextJS to retrieve configuration dynamically when the server starts up. My goal is to have this configuration accessible during runtime for all API routes and server-side components. What would be th ...

Is TypeScript 2.8 Making Type-Safe Reducers Easier?

After reading an insightful article on improving Redux type safety with TypeScript, I decided to simplify my reducer using ReturnType<A[keyof A]> based on the typeof myActionFunction. However, when creating my action types explicitly like this: exp ...

Does Apollo Federation provide support for a code-first development approach?

I have declarations using 'code-first' approach in my project, but now I want to utilize them as microservices. How can I separate my 'typeDefs' and 'resolvers' following Apollo's 'schema-first' methodology? Is ...

Getting the Full Error Message in Axios with React Native Expo

I'm encountering a network error while using Axios with React Native. Previously, when working with React JS on the web, I could console log the error or response and see all the details. However, in Expo, all I get is "Axios error: Network error" wh ...

"String representation" compared to the method toString()

Currently, I am in the process of writing unit tests using jasmine. During this process, I encountered an issue with the following code snippet: let arg0: string = http.put.calls.argsFor(0) as string; if(arg0.search(...) This resulted in an error stating ...

Invoking a method in a derived class upon completion of asynchronous logic within the base class

Currently, I am in the process of building an Angular application. One aspect of my project involves a class that extends a base class. While this approach may not be ideal, I am curious to know what would be the best practice for BaseClass to trigger me ...

Tips for implementing JS function in Angular for a Collapsible Sidebar in your component.ts file

I am attempting to collapse a pre-existing Sidebar within an Angular project. The Sidebar is currently set up in the app.component.html file, but I want to transform it into its own component. My goal is to incorporate the following JS function into the s ...

Express: issue retrieving numbers from request body array

JavaScript / TypeScript Issue: export const updateSettings = catchErrors(async (req, res) => { console.log("updateSettings req.body: ", req.body) const { organizationId, formdata, updatedItems, updateQuota } = req.body; console.lo ...

My requests and responses will undergo changes in naming conventions without my consent or awareness

Initially, I wrote it in a somewhat general manner. If you require more information, please let me know! This is how my C# class appears when sent/received on the frontend: public class Recipe : ICRUD { public Guid ID { get; set; } ...

Struggling to retrieve the 'this' object using a dynamic string

Within my Nuxt + TS App, I have a method that attempts to call a function: nextPage(paginationName: string): void { this[`${paginationName}Data`].pagination .nextPage() .then((newPage: number) => { this.getData(pagination ...

Vanilla JavaScript error: Unable to access property

I am working on implementing a header with a logo and navigation that includes a menu toggle link for smaller viewports. My goal is to achieve this using Vanilla JS instead of jQuery. However, when I click on the menu toggle link, I encounter the followin ...

The routes designed for children in the feature module are malfunctioning

Looking for help with organizing modules in a large app without cluttering the app-routing.module and app.module.ts files. Specifically focusing on managing route paths through featured modules (not using lazy loading at the moment). Encountering issues w ...

Compile time error due to TypeScript enumeration equality issue

Currently, I am developing a system to manage user roles within my website using TypeScript enumeration. This will allow me to restrict access to certain parts of the site based on the user's role. The primary challenge I am facing is comparing the u ...

When using my recursive type on Window or Element, I encounter a type instantiation error stating "Type instantiation is excessively deep and possibly infinite.ts"

Recently, I have been using a type to automatically mock interface types in Jest tests. However, upon updating TypeScript and Jest to the latest versions, I encountered an error message stating Type instantiation is excessively deep and possibly infinite.t ...

Ways to incorporate Bootstrap components into an Angular application without relying on external modules

I'm attempting to activate Bootstrap 5.3 Tooltips within my Angular 17 application. Within angular.json, I've added bootstrap.bundle.min.js, which includes PopperJS. "scripts": [ "node_modules/bootstrap/dist/js/bootstrap.bundle. ...

What could be causing the malfunction of my Nextjs Route Interception Modal?

I'm currently exploring a different approach to integrating route interception into my Nextjs test application, loosely following this tutorial. Utilizing the Nextjs app router, I have successfully set up parallel routing and now aiming to incorporate ...

"Setting up a schema in TypeORM when connecting to an Oracle database: A step-by-step guide

As a newcomer to TypeORM, I'm using Oracle DB with Node.js in the backend. Successfully connecting the database with TypeORM using createConnection(), but struggling to specify the schema during connection creation. One workaround is adding the schem ...