Nicolas Bouvrette
Nicolas Bouvrette

Reputation: 4777

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[] }

Upvotes: 2

Views: 667

Answers (1)

Aifos Si Prahs
Aifos Si Prahs

Reputation: 363

 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

Upvotes: 1

Related Questions