Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use TypeScript's indexed access types with nullable nested types?

I'm trying to define a TypeScript type in terms of another type.

This works:

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

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

But, when the data property is nullable, this doesn't work:

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

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

and results in the error:

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

How can I define my NestedData type in terms of Result, without duplicating any part of Result's typings?

Demo on TypeScript Playground

Edit: I'm getting my NestedData type from a codegen tool and I'm defining NestedData as a shorter type alias. In reality the typing is longer so I want to minimize repetition.

like image 388
ruohola Avatar asked Mar 31 '26 23:03

ruohola


2 Answers

You can use NonNullable to remove null (and undefined) from the union:

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

Playground Link

Equivalently, but a bit more verbosely, you can use Exclude:

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

Playground Link

It makes sense to do it in one of these ways when you can't change your Result type for some reason. In other situations it would be more natural to define them this way round:

type NestedData = { foo: string; bar: string }
type Result = { data: { nestedData: NestedData } | null }
like image 93
kaya3 Avatar answered Apr 02 '26 13:04

kaya3


Generic util for getting nullable properties:

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

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

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

Playground

like image 39
captain-yossarian Avatar answered Apr 02 '26 11:04

captain-yossarian