josias
josias

Reputation: 1626

Typescript: Property type wildcard

I have a given interface which comes from another package, so I can't really change it. For the sake of simplicity, let's just say the following interface:

interface SomeInterface {
   someProp: string;
   someOtherProp?: number;
}

I was wondering if I can somehow extract the types of all properties so I would get a combined type which could be any of the original Interface's properties.

In the example, it would resolve to a type being string | number | undefined.

Also, not really the same question, but quite related to it. Is it possible to extract the allowed properties names instead of values, so in the example given it would be a type holding the values "someProp" | "someOtherProp".

For the first case, I already tried the type SomeInterface[string], but I think that only works when the interface has a key/index signature defined, not specific properties.

Upvotes: 1

Views: 1422

Answers (1)

Maciej Sikora
Maciej Sikora

Reputation: 20132

Get all possible keys of Mapped type by keyof

type Keys = keyof SomeInterface;

Get all possible values of Mapped type by indexed access operator

type Values = SomeInterface[keyof SomeInterface];

Upvotes: 3

Related Questions