How to enforce all members of a union will be present in an array of objects? How to reduce the array to an object with all union members as keys?

    type PoseType = 'front' | 'side' | 'back';
    type PoseInfo = {
        poseType: PoseType,
        data: number,
        other: string
    }
 
    const exampleArray = [
      {
        poseType: 'front',
        data: 1,
        other: 'a'
      },
      {
        poseType: 'side',
        data: 2,
        other: 'b'
      },
      {
        poseType: 'back',
        data: 3,
        other: 'c'
      },
    ]
      
      
    const requiredObject: {[k in PoseType]: PoseInfo}= {
      front:{// <--
        poseType: 'front', //matches the above property
        data: 1,
        other: 'a'
      },
      side:{
        poseType: 'side',
        data: 2,
        other: 'b'
      },
      back:{
        poseType: 'back',
        data: 3,
        other: 'c'
      },
    }
      

How to enforce that:

  1. exampleArray will contain an array with all PoseTypes in poseType
    property
  2. requiredObject will contain all PoseTypes with object.poseType matching the property
  3. How to use Array.reduce, with proper types to achieve this type safety?

2 thoughts on “How to enforce all members of a union will be present in an array of objects? How to reduce the array to an object with all union members as keys?”

Leave a Comment