Advanced TypeScript Types: keyof, typeof, Conditional Types, infer & Mapped Types
Sep 2,2026

Series: TypeScript from Basics to Advanced
Part: 11 — Advanced TypeScript Types
Level: Intermediate → Advanced


Introduction

So far, we've mainly used TypeScript to describe data:

interface User {
  id: number;
  name: string;
  email: string;
}

We've also learned how Generics and Utility Types let us reuse and transform existing types.

Advanced TypeScript takes this further.

Instead of manually defining every type, we can make TypeScript derive new types from existing types.

For example:

type UserKeys = keyof User;

TypeScript creates:

"id" | "name" | "email"

We can also create conditional types:

type IsString<T> =
  T extends string ? true : false;

Or transform every property in an object:

type Optional<T> = {
  [K in keyof T]?: T[K];
};

These capabilities are the foundation behind many of TypeScript's built-in Utility Types and strongly typed libraries.

In this article, we'll cover:

  • keyof

  • typeof

  • Indexed Access Types

  • Conditional Types

  • infer

  • Mapped Types

  • Mapping modifiers

  • Key remapping

  • Template Literal Types

  • Distributive Conditional Types

  • Recursive Types

  • Practical type transformations

  • Hands-on exercises with answers


1. The keyof Operator

keyof creates a union containing the keys of an object type.

Consider:

interface User {
  id: number;
  name: string;
  email: string;
}

Now:

type UserKeys = keyof User;

UserKeys becomes:

"id" | "name" | "email"

So:

const key: UserKeys = "name";

is valid.

But:

const key: UserKeys = "password";

is invalid.

keyof is useful whenever another type should be restricted to the known properties of an object.


2. keyof with Generics

We briefly saw this pattern in Part 9:

function getProperty<
  T,
  K extends keyof T
>(
  object: T,
  key: K
): T[K] {
  return object[key];
}

Now:

const user = {
  id: 1,
  name: "Sundar",
  email: "sundar@example.com"
};

const name = getProperty(user, "name");

TypeScript knows:

name → string

And this fails:

getProperty(user, "password");

because "password" isn't part of keyof User.

The important relationship is:

T
↓
keyof T
↓
valid property names

3. The typeof Operator

JavaScript already has a runtime typeof operator:

typeof "Hello";

which returns:

"string"

TypeScript also allows typeof in a type context.

Suppose we have:

const user = {
  id: 1,
  name: "Sundar",
  active: true
};

Instead of manually creating an interface, we can write:

type User = typeof user;

TypeScript derives:

type User = {
  id: number;
  name: string;
  active: boolean;
};

Now the type follows the original value automatically.


4. keyof typeof

keyof and typeof are often combined.

Consider:

const permissions = {
  read: true,
  write: true,
  delete: false
};

First:

typeof permissions

gets the object's type.

Then:

keyof typeof permissions

gets its keys.

type Permission =
  keyof typeof permissions;

The result is:

"read" | "write" | "delete"

This is useful when a runtime object should also define the allowed values at compile time.


5. Indexed Access Types

Indexed Access Types allow us to extract the type of a specific property.

Consider:

interface User {
  id: number;
  name: string;
  address: {
    city: string;
    country: string;
  };
}

We can extract the name type:

type UserName = User["name"];

Result:

string

Or:

type UserAddress = User["address"];

Result:

{
  city: string;
  country: string;
}

This avoids duplicating nested types.


6. Accessing Nested Types

Indexed access can go deeper.

type City =
  User["address"]["city"];

The result is:

string

This becomes useful when working with large API response types where you need one deeply nested type.


7. Indexed Access with Arrays

Suppose:

interface Question {
  id: string;
  question: string;
}

type Questions = Question[];

To get the type of one array element:

type QuestionItem =
  Questions[number];

The result is:

Question

Another common pattern is:

const users = [
  {
    id: 1,
    name: "Sundar"
  },
  {
    id: 2,
    name: "Rahul"
  }
];

Then:

type User =
  (typeof users)[number];

TypeScript derives the type of each item in the array.


8. Conditional Types

Conditional Types allow TypeScript to choose one type or another based on a condition.

The syntax is:

T extends U ? X : Y

You can read this as:

If T is assignable to U
    ↓
use X
otherwise
    ↓
use Y

For example:

type IsString<T> =
  T extends string
    ? true
    : false;

Now:

type A = IsString<string>;

becomes:

true

while:

type B = IsString<number>;

becomes:

false

9. Returning Different Types Conditionally

Conditional types aren't limited to true and false.

For example:

type ApiResult<T> =
  T extends string
    ? { message: T }
    : { data: T };

Now:

type StringResult =
  ApiResult<string>;

becomes:

{
  message: string;
}

While:

type NumberResult =
  ApiResult<number>;

becomes:

{
  data: number;
}

Conditional types let us express relationships between types at compile time.


10. Conditional Types with never

never is commonly used to remove unwanted types.

For example:

type RemoveNull<T> =
  T extends null
    ? never
    : T;

Given:

type Value =
  string | number | null;

we can write:

type SafeValue =
  RemoveNull<Value>;

The result is:

string | number

This works because never disappears from unions.


11. The infer Keyword

infer allows TypeScript to capture a type from another type inside a conditional type.

For example:

type GetReturnType<T> =
  T extends (...args: any[]) => infer R
    ? R
    : never;

Here:

infer R

means:

If T is a function, infer its return type and store that type in R.

Now:

function getUser() {
  return {
    id: 1,
    name: "Sundar"
  };
}

We can write:

type User =
  GetReturnType<typeof getUser>;

User becomes:

{
  id: number;
  name: string;
}

This is conceptually similar to TypeScript's built-in ReturnType<T>.


12. Using infer with Promises

We can also extract the value inside a Promise.

type UnwrapPromise<T> =
  T extends Promise<infer U>
    ? U
    : T;

Now:

type Result =
  UnwrapPromise<Promise<string>>;

becomes:

string

And:

type Result =
  UnwrapPromise<number>;

remains:

number

The inferred type exists only inside the true branch of the conditional type.


13. Using infer with Arrays

We can extract an array's element type:

type ElementType<T> =
  T extends (infer U)[]
    ? U
    : never;

Now:

type NumberItem =
  ElementType<number[]>;

becomes:

number

And:

type UserItem =
  ElementType<User[]>;

becomes:

User

14. Mapped Types

Mapped Types allow us to iterate over the properties of another type and create a new type.

Consider:

interface User {
  id: number;
  name: string;
  email: string;
}

We can create:

type Optional<T> = {
  [K in keyof T]?: T[K];
};

Now:

type OptionalUser =
  Optional<User>;

becomes conceptually:

{
  id?: number;
  name?: string;
  email?: string;
}

This is essentially how Partial<T> works.


15. Understanding Mapped Type Syntax

The important syntax is:

[K in keyof T]

Think of it like:

Take every key K from T
          ↓
Create that property
          ↓
Use T[K] as its value type

So:

type Copy<T> = {
  [K in keyof T]: T[K];
};

creates a type with the same properties as T.


16. Creating a Readonly Mapped Type

We can add modifiers while mapping properties.

type MakeReadonly<T> = {
  readonly [K in keyof T]: T[K];
};

For:

type ReadonlyUser =
  MakeReadonly<User>;

all properties become readonly.

This is conceptually similar to:

Readonly<User>

17. Mapping Modifiers

Mapped types can add or remove:

?
readonly

For example, to remove optional properties:

type MakeRequired<T> = {
  [K in keyof T]-?: T[K];
};

The:

-?

means:

Remove the optional modifier.

Similarly:

type MakeMutable<T> = {
  -readonly [K in keyof T]: T[K];
};

removes readonly.

The + modifier can explicitly add a modifier, although adding is the default.


18. Changing Property Value Types

Mapped types don't have to preserve the original property types.

For example:

type BooleanFields<T> = {
  [K in keyof T]: boolean;
};

Given:

interface Features {
  darkMode: string;
  notifications: number;
  analytics: object;
}

We can create:

type FeatureFlags =
  BooleanFields<Features>;

Result:

{
  darkMode: boolean;
  notifications: boolean;
  analytics: boolean;
}

Only the property names are preserved.


19. Key Remapping

Mapped Types can also rename keys using as.

For example:

type Getters<T> = {
  [K in keyof T as
    `get${Capitalize<string & K>}`]:
      () => T[K];
};

Given:

interface User {
  name: string;
  age: number;
}

We can create:

type UserGetters =
  Getters<User>;

which becomes:

{
  getName: () => string;
  getAge: () => number;
}

This combines:

  • Mapped Types

  • Key remapping

  • Template Literal Types

  • Capitalize


20. Template Literal Types

Template Literal Types allow us to create string types using template literal syntax.

For example:

type Event =
  "click" | "focus";

We can create:

type EventHandler =
  `on${Capitalize<Event>}`;

The result is:

"onClick" | "onFocus"

Unlike JavaScript template literals, this happens entirely in the type system.


21. Combining Multiple String Unions

Template Literal Types can generate combinations.

type Size =
  "sm" | "md" | "lg";

type Variant =
  "primary" | "secondary";

type ButtonClass =
  `${Size}-${Variant}`;

TypeScript generates:

"sm-primary"
"sm-secondary"
"md-primary"
"md-secondary"
"lg-primary"
"lg-secondary"

This is useful when an application follows predictable naming patterns.


22. Built-in String Manipulation Types

TypeScript provides several built-in helpers for string literal types:

Uppercase<T>
Lowercase<T>
Capitalize<T>
Uncapitalize<T>

For example:

type Role =
  "admin" | "user";

Then:

type UpperRole =
  Uppercase<Role>;

becomes:

"ADMIN" | "USER"

And:

type CapitalRole =
  Capitalize<Role>;

becomes:

"Admin" | "User"

These are particularly useful with Template Literal Types.


23. Distributive Conditional Types

Conditional types behave differently when given union types.

Consider:

type ToArray<T> =
  T extends unknown
    ? T[]
    : never;

Now:

type Result =
  ToArray<string | number>;

TypeScript distributes the condition across each union member.

The result is:

string[] | number[]

It behaves approximately like:

ToArray<string>
      |
ToArray<number>

This behavior is called a Distributive Conditional Type.


24. Preventing Distribution

Sometimes we want the union to be treated as one type.

We can wrap both sides of extends in tuples:

type ToArray<T> =
  [T] extends [unknown]
    ? T[]
    : never;

Now:

type Result =
  ToArray<string | number>;

becomes:

(string | number)[]

This small syntax difference is important in advanced generic libraries.


25. Recursive Types

A Recursive Type refers to itself.

Consider a category structure:

interface Category {
  name: string;
  children?: Category[];
}

Now we can represent nested categories:

const category: Category = {
  name: "Programming",
  children: [
    {
      name: "Frontend",
      children: [
        {
          name: "React"
        }
      ]
    }
  ]
};

Category contains more Category values.

This is recursion at the type level.


26. Recursive JSON Type

Another useful example is JSON data.

type JSONValue =
  | string
  | number
  | boolean
  | null
  | JSONValue[]
  | {
      [key: string]: JSONValue;
    };

This type describes values that can recursively contain arrays and objects of other JSON-compatible values.

For example:

const data: JSONValue = {
  user: {
    name: "Sundar",
    active: true
  },
  scores: [90, 85, 95]
};

27. Practical Example: Type-Safe Event Names

Suppose:

interface User {
  name: string;
  email: string;
}

We want event names such as:

nameChanged
emailChanged

We can generate them:

type UserEvent =
  `${keyof User}Changed`;

The result is:

"nameChanged" | "emailChanged"

Now:

function listen(
  event: UserEvent
) {
  // ...
}

This works:

listen("nameChanged");

But this fails:

listen("passwordChanged");

The event names automatically stay synchronized with the User type.


28. Practical Example: Type-Safe Event Values

We can go further and connect the property name to the callback value.

function onChange<
  T,
  K extends keyof T
>(
  object: T,
  key: K,
  callback: (value: T[K]) => void
) {
  callback(object[key]);
}

Now:

const user = {
  name: "Sundar",
  age: 30
};

When we write:

onChange(
  user,
  "name",
  value => {
    value.toUpperCase();
  }
);

TypeScript knows:

value → string

But with:

onChange(
  user,
  "age",
  value => {
    value.toFixed(2);
  }
);

TypeScript knows:

value → number

This demonstrates how advanced types allow several pieces of an API to remain synchronized.


29. Practical Example: API Response Extraction

Suppose:

interface ApiResponse<T> {
  status: "success" | "error";
  data: T;
}

We can create a type that extracts the data:

type ResponseData<T> =
  T extends ApiResponse<infer D>
    ? D
    : never;

Now:

type UserResponse =
  ApiResponse<User[]>;

type Users =
  ResponseData<UserResponse>;

Users becomes:

User[]

This is useful when working with generic API wrappers.


30. Practical Example: Removing Function Properties

Suppose:

interface UserService {
  name: string;
  version: number;

  login(): void;
  logout(): void;
}

We want a type containing only data properties.

We can combine Mapped Types and Conditional Types:

type DataProperties<T> = {
  [K in keyof T as
    T[K] extends Function
      ? never
      : K
  ]: T[K];
};

Now:

type ServiceData =
  DataProperties<UserService>;

becomes:

{
  name: string;
  version: number;
}

Keys mapped to never are removed.


31. How Utility Types Are Built

Now that we understand advanced types, some Utility Types from Part 10 become easier to understand internally.

For example, a simplified Partial looks like:

type MyPartial<T> = {
  [K in keyof T]?: T[K];
};

A simplified Readonly:

type MyReadonly<T> = {
  readonly [K in keyof T]: T[K];
};

And a simplified Pick:

type MyPick<
  T,
  K extends keyof T
> = {
  [P in K]: T[P];
};

You don't normally need to recreate these built-in utilities.

The value of understanding their implementation is seeing how:

Generics
+
keyof
+
Indexed Access Types
+
Mapped Types

work together.


32. Common Mistakes

Using advanced types when a simple interface is enough

Avoid making a type difficult to understand just because TypeScript supports sophisticated transformations.

Prefer:

interface User {
  id: number;
  name: string;
}

when that already describes the problem clearly.

Advanced types are most valuable when they remove duplication or enforce relationships between types.


Confusing runtime and compile-time operations

This:

type Keys = keyof User;

doesn't create an array of keys at runtime.

Similarly:

type UserType = typeof user;

exists only during type checking.

TypeScript types disappear when JavaScript is generated.


Overusing infer

Use infer when a type genuinely needs to extract another type.

If TypeScript already provides a utility such as:

ReturnType<T>
Awaited<T>
Parameters<T>

prefer the built-in utility unless you're implementing different behavior.


Forgetting conditional type distribution

This:

T extends U ? X : Y

may distribute when T is a union.

If you need to evaluate the entire union:

[T] extends [U] ? X : Y

33. Best Practices

Use advanced types when they make relationships between types safer and reduce duplication.

Keep transformations small and give complicated types descriptive names.

Prefer built-in Utility Types when they already solve the problem.

Use keyof and indexed access types when one type should stay synchronized with another.

Use Conditional Types when the resulting type genuinely depends on another type.

Use infer for extracting types from structured generic types.

Use Mapped Types when the same transformation needs to be applied across object properties.

Avoid turning business logic into unnecessarily complex type-level programming.

The goal is still readable, maintainable TypeScript.


34. Hands-On Exercises

Exercise 1: keyof

Given:

interface Product {
  id: number;
  name: string;
  price: number;
}

Create a type containing all valid property names of Product.


Exercise 2: typeof

Given:

const config = {
  apiUrl: "/api",
  timeout: 5000,
  debug: true
};

Create a TypeScript type from the config object without manually writing an interface.


Exercise 3: Indexed Access

Given:

interface User {
  id: number;
  profile: {
    name: string;
    email: string;
  };
}

Extract the type of profile.

Then extract only the type of email.


Exercise 4: Conditional Type

Create:

type IsNumber<T>

that produces:

true

when T is a number and:

false

otherwise.


Exercise 5: infer

Create:

type ArrayElement<T>

that extracts the element type from an array.

For example:

ArrayElement<string[]>

should produce:

string

Exercise 6: Mapped Type

Create:

type Nullable<T>

that converts every property into:

original type | null

Exercise 7: Template Literal Type

Given:

type Action =
  "save" | "delete" | "update";

Generate:

"onSave"
"onDelete"
"onUpdate"

using a Template Literal Type.


Exercise 8: Recursive Type

Create a MenuItem type containing:

label → string
children → optional array of MenuItem

Use it to represent a nested navigation menu.


Exercise 9: Key Remapping

Given:

interface User {
  name: string;
  email: string;
}

Create a mapped type that produces:

{
  getName: () => string;
  getEmail: () => string;
}

Exercise 10: API Type Extraction

Given:

interface ApiResponse<T> {
  success: boolean;
  data: T;
}

Create:

type ExtractData<T>

using infer.

It should extract T from:

ApiResponse<T>

35. Answers & Solutions

Answer 1

interface Product {
  id: number;
  name: string;
  price: number;
}

type ProductKey =
  keyof Product;

Result:

"id" | "name" | "price"

Answer 2

const config = {
  apiUrl: "/api",
  timeout: 5000,
  debug: true
};

type Config =
  typeof config;

TypeScript derives the object structure automatically.


Answer 3

interface User {
  id: number;
  profile: {
    name: string;
    email: string;
  };
}

type Profile =
  User["profile"];

type Email =
  User["profile"]["email"];

Profile represents the complete profile object.

Email is:

string

Answer 4

type IsNumber<T> =
  T extends number
    ? true
    : false;

For example:

type A = IsNumber<number>;
type B = IsNumber<string>;

Results:

A → true
B → false

Answer 5

type ArrayElement<T> =
  T extends (infer U)[]
    ? U
    : never;

Now:

type A =
  ArrayElement<string[]>;

type B =
  ArrayElement<number[]>;

Results:

A → string
B → number

Answer 6

type Nullable<T> = {
  [K in keyof T]:
    T[K] | null;
};

For:

interface User {
  name: string;
  age: number;
}

Nullable<User> becomes:

{
  name: string | null;
  age: number | null;
}

Answer 7

type Action =
  "save" | "delete" | "update";

type ActionHandler =
  `on${Capitalize<Action>}`;

Result:

"onSave"
| "onDelete"
| "onUpdate"

Answer 8

interface MenuItem {
  label: string;
  children?: MenuItem[];
}

Example:

const menu: MenuItem = {
  label: "Development",
  children: [
    {
      label: "Frontend",
      children: [
        {
          label: "React"
        }
      ]
    },
    {
      label: "Backend"
    }
  ]
};

Answer 9

type Getters<T> = {
  [K in keyof T as
    `get${Capitalize<string & K>}`]:
      () => T[K];
};

Now:

interface User {
  name: string;
  email: string;
}

type UserGetters =
  Getters<User>;

produces:

{
  getName: () => string;
  getEmail: () => string;
}

Answer 10

interface ApiResponse<T> {
  success: boolean;
  data: T;
}

type ExtractData<T> =
  T extends ApiResponse<infer D>
    ? D
    : never;

Now:

type Response =
  ApiResponse<string[]>;

type Data =
  ExtractData<Response>;

Data becomes:

string[]

Bonus Challenge

Let's combine several concepts from this article.

Suppose we have:

interface User {
  id: number;
  name: string;
  email: string;
  active: boolean;
}

Create a type that automatically generates change handlers:

{
  onIdChange: (value: number) => void;
  onNameChange: (value: string) => void;
  onEmailChange: (value: string) => void;
  onActiveChange: (value: boolean) => void;
}

Try solving it before checking the answer.

Solution

type ChangeHandlers<T> = {
  [K in keyof T as
    `on${Capitalize<string & K>}Change`]:
      (value: T[K]) => void;
};

Now:

type UserChangeHandlers =
  ChangeHandlers<User>;

TypeScript generates all four handlers automatically.

If the User interface later gets:

age: number;

TypeScript automatically adds:

onAgeChange:
  (value: number) => void;

to UserChangeHandlers.

This is one of the strongest benefits of advanced TypeScript: related types can stay synchronized without manually updating every type.


Final Takeaway

Advanced TypeScript Types allow us to derive, inspect, transform, and compose types.

The core ideas are:

keyof
→ Get object keys

typeof
→ Get a type from a value

T[K]
→ Get a property's type

Conditional Types
→ Choose types based on conditions

infer
→ Extract a type from another type

Mapped Types
→ Transform object properties

Template Literal Types
→ Generate string literal types

Distributive Conditional Types
→ Apply conditions to union members

Recursive Types
→ Describe nested/self-referencing structures

You don't need to use these features everywhere.

The important skill is recognizing situations where a type already contains the information you need.

Instead of manually duplicating that information, TypeScript can often derive it.

For example:

type Keys = keyof User;

instead of manually maintaining:

type Keys =
  "id" | "name" | "email";

Or:

type Email =
  User["email"];

instead of repeating:

type Email = string;

As your TypeScript codebase grows, these relationships help prevent different types from drifting out of sync.