Home > Mobile >  how to use type as key of another type?
how to use type as key of another type?

Time:12-05

As shown in the example below, I'm trying to make this behavior, as I want to pass the component name dynamically alongside its props

any suggestions?

as the current implementation is not working as expected


type AllowedComponents = 'A' | 'B' | 'C'

type StepProps = {
  A: AProps,
  B: BProps,
  C: CProps
}

function someFn(componentName:AllowedComponents, props : stepProps[typeof componentName] ){
....
}

CodePudding user response:

You want someFn() to be generic, as follows:

function someFn<K extends AllowedComponents>(componentName: K, props: StepProps[K]) { }

The generic type parameter K is constrained to the AllowedComponents type, so it can only be one of the allowed component names. And the componentName parameter is of type K. The props parameter is of the indexed access type StepProps[K], so its type will be the props type for the given componentName.

In this way, the someFn() function can be used to pass a component name and its corresponding props to a function in a type-safe way. Here's an example of how you might use it:

declare const aProps: AProps;
declare const bProps: BProps;
someFn("A", aProps); // okay!
someFn("A", bProps); // error!

Playground link to code

  • Related