Looking to create a TypeScript type based on another type.
This method is successful:
type Result = { data: { nestedData: { foo: string; bar: string } } };
type NestedData = Result['data']['nestedData'];
However, when the data
property can be null, the following approach fails:
type Result = { data: { nestedData: { foo: string; bar: string } } | null };
type NestedData = Result['data']['nestedData'];
resulting in the error message:
Property 'nestedData' does not exist on type '{ nestedData: { foo: string; bar: string; }; } | null'.(2339)
Is there a way to define the NestedData
type based on the Result
type without repeating any part of the original typings?
Check out the demo on TypeScript Playground
Edit: I'm working with a tool generating my NestedData
type and I'm defining NestedData
as a concise type alias. The actual typing is more complex, so I aim to reduce redundancy.