网站搜索

严格空值检查下可选属性内部属性的 TypeScript 类型


考虑以下接口:

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

现在我想访问 'child' 的类型。通常我会这样做:

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

但是,当启用 strict-null-checks 模式时,我不幸遇到了以下错误:

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

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

我尝试使用非空断言操作符:

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

但是我收到了那个错误:

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

上帝知道那意味着什么……

有什么方法可以获取这里‘child’的类型吗?

答案#1

你只需将 undefined 从 parent 的类型中排除即可:

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

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