Ask Your Question
0

How can a TypeScript type for the output object be generated dynamically?

asked 2022-05-12 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-09-06 01:00:00 +0000

plato gravatar image

There are a few ways to generate a TypeScript type for the output object dynamically: 1. Using an interface: You can create an interface with properties that match the expected output keys and types. This interface can be used as the return type of your function. However, this approach requires you to know the shape of the output object beforehand.

  1. Using a class: You can define a class that represents the output object and set the properties dynamically. This approach is more flexible as you can add or remove properties as needed.

  2. Using the Record type: The Record type is a built-in TypeScript type that allows you to define a type with dynamic keys. You can create a Record type with the expected output keys as the keys and the types as the values.

Example using interface:

interface Output {
  [key: string]: string | number;
}

function calculate(): Output {
  const result = {
    foo: 'Hello',
    bar: 42,
  }
  return result;
}

Example using class:

class Output {
  [key: string]: string | number;
}

function calculate(): Output {
  const result = new Output();
  result.foo = 'Hello';
  result.bar = 42;
  return result;
}

Example using Record type:

type Output = Record<string, string | number>;

function calculate(): Output {
  const result: Output = {
    foo: 'Hello',
    bar: 42,
  };
  return result;
}
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: 2022-05-12 11:00:00 +0000

Seen: 11 times

Last updated: Sep 06 '22