We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Extracting Keys from Types

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"

Assignment

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.