Ask Your Question
3

How can an array of objects containing different types be mapped using a discriminated union in TypeScript?

asked 2023-06-25 02:45:18 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-25 02:56:01 +0000

woof gravatar image

To map an array of objects containing different types using a discriminated union in TypeScript, you can follow these steps:

  1. Define a discriminated union type that includes all the possible types of objects in the array. For example:
type MyObject = {
  type: 'type1',
  foo: string,
} | {
  type: 'type2',
  bar: number,
} | {
  type: 'type3',
  baz: boolean,
};
  1. Declare an array of objects of type MyObject:
const myObjects: MyObject[] = [
  {type: 'type1', foo: 'hello'},
  {type: 'type2', bar: 42},
  {type: 'type1', foo: 'world'},
  {type: 'type3', baz: true},
];
  1. Use the switch statement to map each object in the array based on its type property:
const mappedObjects = myObjects.map(obj => {
  switch (obj.type) {
    case 'type1':
      return obj.foo.toUpperCase();
    case 'type2':
      return obj.bar.toString();
    case 'type3':
      return obj.baz ? 'yes' : 'no';
  }
});

In this example, mappedObjects is an array of strings that corresponds to the original array of objects. Each object is mapped to a string based on its type. Note that the switch statement can include any number of cases depending on how many types there are in the discriminated union.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-25 02:45:18 +0000

Seen: 13 times

Last updated: Jun 25 '23