1

I have something like this

const one = { 
       props: {
              num:2
      }
}
const two ={
       props: {
            name: 'j' 
      }
}

const packages = [one,two]

Now I would like create a variable which is merged props of packages variable look like this

Type CombineProps = {
    num: number
    name: string
}

By using reduce(Array) but it can't work in typescript

const props = package.reduce(previous, item => {...previous, ...item.props},{}) 

How can I make resolve this? Thanks

Tom Le
  • 117
  • 10

1 Answers1

1

Typescript can't infer the type of the result in this case. We can build a type that is an intersection of the props using UnionToIntersection (don't forget to upvote the linked answer) and a few type queries:

const one = { 
    props: {
            num:2
    }
}
const two ={
    props: {
            name: 'j' 
    }
}

const packages = [one, two]

type UnionToIntersection<U> = (U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never

const props = packages
    .reduce((previous, item) => ({ ...previous, ...item.props }), {} as UnionToIntersection<typeof packages[number]['props']>)

props.name // string
props.num // number
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357