TypeScript: Create a condition-based subset types

Deep dive into typing system to solve THE ultimate riddle

Piotr Lewandowski
Jun 23, 2018 · 6 min read
Photo by Alvaro Reyes on Unsplash

TL;DR; Source code of experiment. Solution.

In this article, we’re going to experiment with TypeScript 2.8 conditional and mapping types. The goal is to create a type that would filter out all keys from your interface, that aren’t matching condition.

You don’t have to know details of what mapping types are. It’s enough to know that TypeScript allows you to take an existing type and slightly modify it to make a new type. This is part of its Turing Completeness.

You can think of type as function — it takes another type as input, makes some calculations and produces new type as output. If you heard of Partial<Type> or Pick<Type, Keys>, this is exactly how they work.

📐Let’s define the problem

We want to extract only keys of a given type, such as only functions that returns Promise or something more simple like key of type number.

We need a name and definition. Let’s say: SubType<Base, Condition>

We have defined two generics by which will configure SubType:

  • Base — the interface that we’re going to modify.
  • Condition — another type, this one telling us which properties we would like to keep in the new object.

Input

interface Person {
id: number;
name: string;
lastName: string;
load: () => Promise<Person>;
}

Expected outcome

// SubType<Person, string> 

type SubType = {
name: string;
lastName: string;
}

📈Step by step to a solution

Step 1 — Baseline

type FilterFlags<Base, Condition> = {
[Key in keyof Base]:
Base[Key] extends Condition ? Key : never
};

For each key, we apply a condition. Depending on the result, we set the name as the type or we put never, which is our flag for keys that we don’t want to see in the new type. It’s a special type, the opposite of any. Nothing can be assigned to it!

Look how this code is evaluated:

FilterFlags<Person, string>; // Step 1FilterFlags<Person, string> = { // Step 2
id: number extends string ? 'id' : never;
name: string extends string ? 'name' : never;
lastName: string extends string ? 'lastName' : never;

load: () => Promise<Person> extends string ? 'load' : never;
}
FilterFlags<Person, string> = { // Step 3
id: never;
name: 'name';
lastName: 'lastName';
load: never;
}

Note: 'id' is not a value, but a more precise version of the string type. We’re going to use it later on. Difference between string and 'id' type:

const text: string = 'name' // OK
const text: 'id' = 'name' // ERR

Step 2 — List of keys that match type condition

type AllowedNames<Base, Condition> = 
FilterFlags<Base, Condition>[keyof Base]

We’re using the code from the previous step and adding only one more part: [keyof Base]
What this does is gather the most common types of given properties and ignore never (as those can’t be used anyway).

type family = {
type: string;
sad: never;
members: number;
friend: 'Lucy';
}
family['type' | 'members'] // string | number
family['sad' | 'members'] // number (never is ignored)
family['sad' | 'friend'] // 'Lucy'

Above, we have an example of returning string | number. So how can we get names? In the first step we replaced the type of key with its name!

type FilterFlags = {
name: 'name';
lastName: 'lastName';
id: never;
}
AllowedNames<FilterFlags, string>; // 'name' | 'lastName'

We’re close to a solution now.


Now we’re ready to build our final object. We just use Pick, which iterates over provided key names and extracts the associated type to the new object.

type SubType<Base, Condition> = 
Pick<Base, AllowedNames<Base, Condition>>

Where Pick is a built-in mapped type, provided in TypeScript since 2.1:

Pick<Person, 'id' | 'name'>; 
// equals to:
{
id: number;
name: string;
}

🎉Full Solution

type FilterFlags<Base, Condition> = {
[Key in keyof Base]:
Base[Key] extends Condition ? Key : never
};
type AllowedNames<Base, Condition> =
FilterFlags<Base, Condition>[keyof Base];
type SubType<Base, Condition> =
Pick<Base, AllowedNames<Base, Condition>>;

Note: This is only typing system code, can you imagine that making loops and applying if statements might be possible?

Some people prefer to have types within one expression. You ask, I provide:

type SubType<Base, Condition> = Pick<Base, {
[Key in keyof Base]: Base[Key] extends Condition ? Key : never
}[keyof Base]>;

🔥 Usages

type JsonPrimitive = SubType<Person, number | string>;// equals to:
type JsonPrimitive = {
id: number;
name: string;
lastName: string;
}
// Let's assume Person has additional address key
type JsonComplex = SubType<Person, object>;
// equals to:
type JsonComplex = {
address: {
street: string;
nr: number;
};
}

2. Filter out everything except functions:

interface PersonLoader {
loadAmountOfPeople: () => number;
loadPeople: (city: string) => Person[];
url: string;
}
type Callable = SubType<PersonLoader, (_: any) => any>// equals to:
type Callable = {
loadAmountOfPeople: () => number;
loadPeople: (city: string) => Person[];
}

If you find any other nice use cases, show us in a comment!

🤔 What this solution won’t solve?

// expected: Nullable = { city, street }
// actual: Nullable = {}
type Nullable = SubType<{
street: string | null;
city: string | null;
id: string;
}, null>

2. RunTime filtering — Remember that types are erased during compile-time. It does nothing to the actual object. If you would like to filter out an object the same way, you would need to write JavaScript code for it.

Also, I would not recommend using Object.keys() on such a structure as runtime result might be different than given type.

Summary

I like how TypeScript is easy to learn yet hard to master. I constantly discover new ways to solve problems that came up in my daily duties. As follow up, I highly recommend reading advanced typing page in the documentation.

The inspiration for this post comes from a StackOverflow question asking exactly this problem. If you like solving riddles, you might also be interested in what Dynatrace is doing with the software.

If you’ve learned something new, please:

→ clap 👏 button below️ so more people can see this
follow me on Twitter (@constjs) so you won’t miss future posts:

DailyJS

JavaScript news and opinion.

Thanks to Tomasz Szreder and Daniel Pieniazek

Piotr Lewandowski

Written by

JavaScript performance-solver at @Dynatrace. JavaScript trouble-maker on my own

DailyJS

DailyJS

JavaScript news and opinion.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade