I have an enum of accepted Providers, a type Provider and an interface with a providers options. I would like in my ComponentProps that the options providers should be an object with one of the providersEnum as the key and the provider type as value (but the number of object properties may vary).
export enum Providers{
facebook="facebook",
google="google"
}
export type Provider = {
id:string;
name:string;
}
export interface ComponentProps{
providers: XXX?
}
export const Component = ({providers}: ComponentProps) => {
return <>
{providers?.facebook && "Has Facebook"} {providers?.google && "Has Google"}
</>;
}
// This should be a valid prop :
<Component providers={{
facebook: {
id: 'test',
name: 'test'
}
}}/>
What should I put in the XXX? in the ComponentProps ?
CodePudding user response:
You can use Record
or create a type.
Record example:
export interface ComponentProps {
providers: Record<Providers, Provider>;
}
Custom type (record is just a shorthand for writing your own type):
type ProviderMap = { [key in Providers]: Provider }
export interface ComponentProps {
providers: ProviderMap
}
Of course you can also set your Record to a named type separately as well, like this:
type ProviderMap = Record<Providers, Provider>
Read more about Record
in the official docs