Home > Enterprise >  How to retrieve the type of element from typed array with undefined?
How to retrieve the type of element from typed array with undefined?

Time:10-05

I have an array of type X[] | undefined, I want to extract X type from it and use it after.

what I have tried is:

type X = typeof X[number]

but it gives syntax error because of the undefined.

CodePudding user response:

You need to exclude the undefined from the type first. You can use NonNullable:

declare const X: string[] | undefined
type XItem = NonNullable<typeof  X>[number]

Playground Link

  • Related