简体   繁体   中英

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM