Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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;
}