考虑以下界面:
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.
上帝知道那是什么意思...
有什么办法在这里得到“孩子”的类型吗?
答案 0 :(得分:3)
您只需要从undefined
的类型中排除parent
:
interface MyInterface {
parent?: {
child: { a: number }
}
}
type ChildType = Exclude<MyInterface['parent'], undefined>['child']