Issue
I am unable to create union type from Map. Here is a simple example of what I am trying to do:
const myMap = new Map ([
['one', <IconOne/>],
['two', <IconTwo/>],
['three', <IconThree/>],
]);
// I know i can make it not like Map. But I have data like Map, and can't change it now.
type Props = {
name: 'one' | 'two' | 'three';
// i need this type here, but have no idea how to make this type from map keys
// tryed use "typeof" "keyof" but have no idea how to do it right
}
export const Component = ({name}: Props) => (
<div>
{myMap.get(name)}
</div>
)
Solution
You will need to change the Map
definition to use as const
(otherwise you just get string
as the key type), then you can write
const myMap = new Map ([
['one', <IconOne/>],
['two', <IconTwo/>],
['three', <IconThree/>],
] as const);
type Props = {
name: typeof myMap extends Map<infer K, any> ? K : never;
}
Answered By - Bergi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.