Shachar Har-Shuv
Shachar Har-Shuv

Reputation: 822

typescript type of a property inside an optional property in strict null checking

Consider the following interface:

interface MyInterface {
  parent?: {
    child: { ... }
  }
}

Now I want to access the type of 'child'. Normally I would do that:

type ChildType = MyInterface['parent']['child']

But, when enabling strict-null-checks mode, I unfortunately get the following error:

TS2339: Property 'child' does not exist on type '{ child: { ... }} | undefined`.

That makes sense, because it's indeed not a property of undefined.

I tried using the non-null-assertion-operator:

type ChildType = MyInterface['parent']!['child']

But I got that error:

TS8020: JSDoc types can only be used inside documentation comments.

God knows what that means...

Any way to get the type of 'child' here?

Upvotes: 2

Views: 672

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

You just need to exclude undefined from the type of parent:

interface MyInterface {
  parent?: {
    child: { a: number }
  }
}

type ChildType = Exclude<MyInterface['parent'], undefined>['child']

Upvotes: 4

Related Questions