Reputation: 822
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?
Upvotes: 2
Views: 672
Reputation: 249466
You just need to exclude undefined
from the type of parent
:
interface MyInterface {
parent?: {
child: { a: number }
}
}
type ChildType = Exclude<MyInterface['parent'], undefined>['child']
Upvotes: 4