Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object with the same keys as another object in typescript?

Tags:

typescript

I have a method produce 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 conditions object.

like image 538
Dejan Toteff Avatar asked Oct 01 '17 10:10

Dejan Toteff


People also ask

Can object have same keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

What does Keyof mean in TypeScript?

The keyof type operatorThe keyof operator takes an object type and produces a string or numeric literal union of its keys. The following type P is the same type as “x” | “y”: type Point = { x : number; y : number }; type P = keyof Point ; type P = keyof Point.

How do you use a key in TypeScript?

Use the keyof typeof syntax to create a type from an object's keys, e.g. type Keys = keyof typeof person . The keyof typeof syntax returns a type that represents all of the object's keys as strings.


1 Answers

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.

like image 140
jonrsharpe Avatar answered Oct 13 '22 22:10

jonrsharpe