SILENT
SILENT

Reputation: 4268

Typescript type of optional property within complex type object

I'm trying to get the type of an optional property found within a complex type as shown in the example below. It's probably simple to solve but I haven't able to find the solution.

type ComplexType = {
    lvl0: {
        title: string;
        lvl1: {
            title: string;
            lvl2?: {
                title: string;
                lvl3: {
                    title: string;
                }
            }[]
        }[]
    }[]
}

type lvl3Type = ComplexType["lvl0"][0]["lvl1"][0]["lvl2"][0]["lvl3"];

Typescript Playground

There's an error with the last [0]. How would I get the lvl3Type to resolve?

Upvotes: 2

Views: 513

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95634

Your error, emphasis mine:

Property '0' does not exist on type '{ title: string; lvl3: { title: string; }; }[] | undefined'.

As in your question title, lvl2 is optional: it's defined as lvl2?. If lvl2 is undefined, lvl2[0] will throw an error, so TypeScript is telling you that you can't apply [0] to a type that might be undefined.

Use the utility type NonNullable<T> to avoid the issue and get the type you want.

type lvl3Type =
    NonNullable<ComplexType["lvl0"][0]["lvl1"][0]["lvl2"]>[0]["lvl3"];

Unfortunately you'll need a utility like this instead of !, as kaya3 noted in the comments: The ! only applies to expressions, not types, to indicate that the expression value is not null or undefined.

Upvotes: 4

Related Questions