

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Conditional Types
incomplete
2: Infer
incomplete
3: Mapped Types
incomplete
4: Mapped Types With Conditionals
incomplete
5: Extracting Keys from Types
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Mapped types don't just let you build new object types – they can also be used to extract keys. Say we have this object type:
type Soldier = {
name: string;
age: number;
branch: "garrison" | "military police" | "survey corps";
};
Now imagine you want to get just the keys of the fields that are string-based – maybe for a filter, a dropdown, or feeding to an LLM that summarizes records. First, we create an object where each key either returns the key name, or never:
type StringKeys<T> = {
[K in keyof T]: T[K] extends string ? K : never;
};
That gives you something like:
type Result = {
name: "name";
age: never;
branch: "branch";
};
Now we index into that type using all of its keys:
type StringKeyUnion<T> = StringKeys<T>[keyof T];
We've made the object into a union of its values:
type Keys = StringKeyUnion<Soldier>;
// "name" | "branch"
Support.ai is building a "signal weighting" tool. They want to automatically pull numeric fields from a given type and let engineers assign weights to them.