Home > OS >  How to extract inner property's type from a possibly undefined type
How to extract inner property's type from a possibly undefined type

Time:08-13

I have the following type

type User = { user?: { subscription?: {...} | null | undefined, ... } | null | undefined };

I want to get the type of subscription, i.e. I want to do something like

type SubscriptionType = User['user']['subscription'];

but TS Server throws the following error and the type of SubscriptionType is set to any

typescript: Property 'subscription' does not exist on type '{ __typename?: "users" | undefined; subscription?: { __typename?: "subscriptions" | undefined; id: number; activeSince?: any; renewalDate?: any; endingDate?: any; ... 7 more ...; } | null | undefined; } | null | undefined'.

I cannot define this type myself as it's being generated by graphql codegen and would change whenever the graphql query changes.

CodePudding user response:

We can use the Exclude utility type.

type SubscriptionType = Exclude<User["user"], null | undefined>["subscription"]

Playground

  • Related