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

时间:2019-05-06 14:50:07

标签: typescript

考虑以下界面:

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

现在,我要访问“孩子”的类型。通常我会这样做:

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

但是,启用strict-null-checks模式时,我不幸出现以下错误:

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

这是有道理的,因为它确实不是undefined的属性。

我尝试使用non-null-assertion-operator:

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

但是我遇到了这个错误:

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

上帝知道那是什么意思...

有什么办法在这里得到“孩子”的类型吗?

1 个答案:

答案 0 :(得分:3)

您只需要从undefined的类型中排除parent

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

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