#How to map components and its prop types to an enum map?

7 messages · Page 1 of 1 (latest)

woeful nest
#

I want to create a type for a map of enum keys to React FCs as mentioned in the code snippet below. The type should have enum keys associated to a particular component and its corresponding props. I tried a couple other methods but nothing works because the prop types for each component as also different in shape and value.

Here is the sample playground link for this case

manic mantleBOT
#

@woeful nest Here's a shortened URL of your playground link! You can remove the full link from your message.

brucewayne2206#0

Preview:```ts
const enum EDirection {
Up,
Down,
}

type UpPropsType = {success: number}
type DownPropsType = {failure: number; reason: string}

const UpComponent = (upProps: UpPropsType) => (
<>MOVING UP</>
)
const DownComponent = (upProps: DownPropsType) => (
<>MOVING DOWN</>
)
...```

thick mauve
#

I'm not sure you can use Record like that, I think you have to make it an object type, something like this:

type TDirectionToProps = {
    [EDirection.Up]: UpPropsType;
    [EDirection.Down]: DownPropsType;
};

type TDirectionMap = {
    [K in EDirection]: React.FC<TDirectionToProps[K]>;
};

const verticalDirMap: TDirectionMap = {
    [EDirection.Up]: UpComponent,
    [EDirection.Down]: DownComponent
};

woeful nest
#

Awesome thanks @thick mauve . I’ll probably go with this one. But I’m wondering can this be achieved without defining a another map TDirectionToProps for prop types? Like directly inferring from FC definition or something? Because in this way, we might have to maintain another map with props.

thick mauve
#

I don't think it's possible without defining the object first,
the reason the map was added was to do a map between the props to direction, if it cannot do infer the mapping before it exists, it can only infer it after the match was already done,
if you can do it by the object first would be like this:

const enum EDirection {
  Up,
  Down,
}

type UpPropsType = { success: number };
type DownPropsType = { failure: number; reason: string };

const UpComponent: React.FC<UpPropsType> = (upProps: UpPropsType) => <>MOVING UP</>;
const DownComponent: React.FC<DownPropsType> = (upProps: DownPropsType) => <>MOVING DOWN</>;

const verticalDirMap = {
    [EDirection.Up]: UpComponent,
    [EDirection.Down]: DownComponent
};

type TVerticalDirMap = typeof verticalDirMap;
woeful nest
#

Sure Thanks @thick mauve