How can I get the type of a variable that is wrapped in a Maybe
type?
In this case, the implementation of Maybe
is:
type Maybe<T> = T | null
Let's assume I have a data that are typed like that:
type MyData = { postTitle: string } & { meta: Maybe<{ tags: Array<El> }> }
I need to pluck the type of El to use it elsewhere.
I'm a TS noob. I've realize that it's pretty easy to get any nested type if it is not wrapped, like type Easy= Simple['one']['heyAnArrayHere'][number]['propOfArrayElement']
but once Maybe comes in a way, I am done.
I think that I need a conditional type, possibly something like
type Expand<T> = T extends Maybe<infer U> ? U : T
,
but that doesn't work at all.
Any help would be appreciated!
CodePudding user response:
You are looking for the NonNullable<Type>
utility:
type El = HTMLElement;
type Maybe<T> = T | null;
type MyData = { postTitle: string } & { meta: Maybe<{ tags: Array<El> }> }
type AlsoEl = NonNullable<MyData['meta']>['tags'][number];