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 merge object property types in Typescript?

I found several similar questions on this topic but more around object property and not their type. Basically my question is simple:

type Params = StringParam | StringArrayParam
type StringParam = { [parameter: string]: string }
type StringArrayParam = { [parameter: string]: string[] }
const parameters: Params = { entry1: ['hi', 'hello'], entry2: 'hi there' }

I’m trying to get Params to become { [parameter: string]: string | string[] } but neither | or & seem to work because they see StringParam and StringArrayParam as independent types.

Is there a way to actually merge the types so that the same property can have both string | string[] as a value or is my only option to define type Params = { [parameter: string]: string | string[] }

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 :

 type Params = {
    [Property in keyof StringParam]: string | StringArrayParam[Property];
  }
  type StringParam = { [parameter: string]: string }
  type StringArrayParam = { [parameter: string]: string[] }

  const parameters: Params = { entry1: ['hi', 'hello'], entry2: 'hi there' }
  
  console.log(parameters);

Typescript playground

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