Home > Blockchain >  Typescript: Trying to extract a complex type that’s nested within another type using [k: string]
Typescript: Trying to extract a complex type that’s nested within another type using [k: string]

Time:07-07

I am looking to extract a complex type that is nested within a predefined object type.


// The 'events?' property is an extensive definition I would like to extract and use independently
type EventsCollection = { [k: string]: { name: string, events?: ComplexDefinition, desc: string }}

I have tried a number of ways to accomplish this, most have been similar to these, but none have worked so far.

type Events = { [P in keyof EventsCollection ]: EventsCollection[P] }

// and

type Events = { [P in keyof EventsCollection ]: EventsCollection[P]['events'] }

//and

type key = 'events'
type Events = { [P in keyof EventsCollection ]: Required<EventsCollection[P][key]> }

Any ideas how I can accomplish this?

CodePudding user response:

You can use the fact that any keyof EventsCollection (i.e. any string) is defined as having the same value types in EventsCollection. Then you can use any key of that type to select the known events key of the inner type.

type Events = Required<EventsCollection[keyof EventsCollection]>["events"];

See it in the playground.

CodePudding user response:

I think you're trying a bit too hard. You do not need a mapped type.

type Test = NonNullable<EventsCollection[string]['events']>

You just drill in with [] until you get to ComplexDefinition | undefined, and then wrap that in a NonNullable to remove the undefined.

See playground

  • Related