Dejan Toteff Dejan Toteff - 3 years ago 159
TypeScript Question

Object with the same keys as another object in typescript?

I have a method

with the following signature:

interface ProduceConditions {
[key: string]: Function|Promise<any>;

produce(conditions: ProduceConditions, input: any): Promise<object>|object;

The thing is that the returned (resolved) object has the same keys as the

Answer Source

If I understand what you're asking correctly, your input conditions will be an implementation of ProduceConditions with some set of keys, and the return value (whether or not wrapped in a promise) will have the same keys but with the values all resolved.

In which case, the signature you're looking for would be something like:

produce<T extends ProduceConditions, U extends { [key in keyof T]: any }>(conditions: T, input: any): Promise<U> | U

Here I've used two generic types to represent the input and the output, with the requirement that the input type T meets the definition of ProduceConditions and the output type U has the same keys as T.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download