Splox
Splox

Reputation: 761

Is there a way to extract only values of a certain type of an interface in Typescript?

I have been trying to get the following to work with conditional and mapped types to no avail. I might be missing something obvious, but suppose I had the interface:

interface TestInterface {
    x: 1,
    y: "hello"
}

Is there a way to get just this:

interface TestInterfaceButJustStrings {
    y: "hello"
}

Like this:

type ExtractValues<T, U> = /* ??? */;
type TestInterfaceButJustStrings = ExtractValues<TestInterface, string>;

Where ExtractValues<T, U> is type T with only properties whose values match the type U?

Upvotes: 2

Views: 688

Answers (1)

Splox
Splox

Reputation: 761

Okay! Thanks to @VLAZ I was able to figure it out. Solution:

type MatchingValues<T, U> = {
    [K in keyof T]: T[K] extends U ? K : never
}[keyof T];

type ExtractValues<T, U> = Pick<T, MatchingValues<T, U>>;

First, MatchingValues creates a union of all keys that extend type U.

Then, the Pick creates a new type that only has the properties of T that are also in MatchingValues. So, we end up with a type that only has properties that match our U type.

Upvotes: 2

Related Questions