简体   繁体   English

在严格的null检查中,可选属性内的属性的typescript类型

[英]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: 但是,当启用strict-null-checks模式时,不幸的是出现以下错误:

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

That makes sense, because it's indeed not a property of undefined. 这是有道理的,因为它确实不是undefined的属性。

I tried using the non-null-assertion-operator: 我尝试使用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 : 您只需要从parent类型中排除undefined

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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