Dilame Nickolson
Dilame Nickolson

Reputation: 91

How to reduce array of unique-discriminator union objects into object with key of discriminator type and value of related union item

I have an array of discriminated union objects

type Discriminated = {
  discriminator: 'a'
  a: string;
} | {
  discriminator: 'b',
  b: number;
}

const arr: Discriminated[] = [
  {
    discriminator: 'a',
    a: 'hello'
  },
  {
    discriminator: 'b',
    b: 1
  }
];

The discriminator field is guaranteed to be unique across one array. I need to reduce this array into


{
  a: { a: 'hello' },
  b: { b: 1 }
}

I implemented a mapped type for this purpose

type Mapped = {
  [D in Discriminated as D['discriminator']] ?: D;
}

But if i reduce in a naive way i get i receive a fair error

arr.reduce((acc: Mapped, curr) => {
  acc[curr.discriminator] = curr;
  return acc;
}, {} as Mapped)
Type 'Discriminated' is not assignable to type 'undefined'.
  Type '{ discriminator: "a"; a: string; }' is not assignable to type 'undefined'.(2322)

I understand why this error is emitted, but i don't understand how to achieve the goal in a type-safe way with no dirty hacks like type-casting to any or something

Upvotes: 0

Views: 59

Answers (0)

Related Questions