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.
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.
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;
}
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
Asked: 2022-05-12 11:00:00 +0000
Seen: 11 times
Last updated: Sep 06 '22
How can one ensure that sub-classes have uniform method parameters in TypeScript?
Can a TypeScript definition for icon names be provided in MaterialCommunityIcons for React Native?
How can I deal with Expression.Error related to a column in Power Query?
How can you implement pagination in Oracle for the LISTAGG() function?
What is the process for implementing a FutureBuilder on an OnTap function in Flutter?
How can we require users to be logged in before they can access the root folders in WordPress?
In SCSS, what is the method for grouping and reusing a set of classes and styles?