Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write generic properties object in typescript

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading