Creating a type from nested interface properties in TypeScript
While at work I was upgrading graphql-code-generator, and found that the generated code no longer exports the type for a query node. Instead, the type of the whole query response was exported. But I had code that relied on having the node type available.
To solve this, I created a new type by reading attributes from deep in the response type.
interface Foo {
bar: {
baz: {
zap: {
zoop: number;
}[];
};
};
}
type zoop = Foo['bar']['baz']['zap'][number]['zoop'];
If some of your properties are optional, you can use Required<T>
. If they're possibly undefined
, use Exclude<T, undefined>
.