iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐠

Custom Utility Types in Next.js Internals: Mastering Type Manipulation via Optional Property Key Extraction

に公開
2025/09/17

Introduction

While looking at the internal implementation of Next.js, I noticed several custom-defined utility types being used instead of built-in TypeScript utility types like Pick or Partial. I would like to explore the mechanisms and use cases for these types.

The version of Next.js I am looking at is 15.3.4, the latest at the time of writing. However, the types themselves were added back in 2020 and will work with older versions of TypeScript as well.

https://github.com/vercel/next.js/pull/15953

Types for Extracting Only Required/Optional Property Keys

Next.js provides a <Link> component, which is an enhanced version of the <a> tag. It enables soft navigation (client-side routing) and prefetch (preloading pages and data).

https://nextjs.org/docs/pages/api-reference/components/link

This <Link> component is located in the link.tsx file. This file defines custom utility types that take an object type as a type argument to construct a type that extracts only the required property keys, or conversely, a type that extracts only the optional property keys of that object.

An optional property is one marked with a ?, such as {foo?: string}. An object will not cause a type error even if this property is missing.
Conversely, a property without the ? is a required property, and any object lacking such a property will result in a type error.

https://zenn.dev/axoloto210/scraps/2caa329b85f519#comment-1c280566552fa7

The link.tsx mentioned below is the one used in the Pages Router.
The version for the App Router is located at packages/next/src/client/app-dir/link.tsx, where the same types are defined.

https://github.com/vercel/next.js/blob/v15.3.4/packages/next/src/client/link.tsx#L24-L29

https://github.com/vercel/next.js/blob/v15.3.4/packages/next/src/client/app-dir/link.tsx#L26-L31

RequiredKeys Type

The RequiredKeys type is a custom utility type that creates a type by extracting only the required property keys from an object type.
When you pass an object type T, it results in a union type of string literals for the required property keys of T.

type RequiredKeys<T> = {
  [K in keyof T]-?: {} extends Pick<T, K> ? never : K
}[keyof T]

Let's see what kind of type we get when passing an "object type with multiple required and optional properties" to the type argument of RequiredKeys.
The following object type Obj contains three required properties and three optional properties.
Even if a property is a union with undefined, like requiredUndefinedOrNumber: number | undefined;, it is considered a required property as long as it doesn't have the ? modifier.

type Obj = {
  requiredString: string;
  requiredObject: {
    required: string;
    optional?: string;
  };

  optionalString?: string;
  optionalObject?: {
    required: string;
    optional?: string;
  };

  requiredUndefinedOrNumber: number | undefined;
  optionalUndefinedOrNumber?: number | undefined;
};

When we pass this Obj type to the type argument of RequiredKeys, it indeed results in a union type of the required property keys.

type Test = RequiredKeys<Obj>;
//    ^? type Test = "requiredString" | "requiredObject" | "requiredUndefinedOrNumber"

OptionalKeys Type

This is a type for extracting only the keys of optional properties. It differs from the RequiredKeys type in the branching part of the conditional type.

type OptionalKeys<T> = {
  [K in keyof T]-?: {} extends Pick<T, K> ? K : never
}[keyof T]

When we pass the Obj type, we can see that only the keys of the optional properties are retrieved.

type Test2 = OptionalKeys<Obj>;
//   ^? type Test2 = "optionalString" | "optionalObject" | "optionalUndefinedOrNumber"

Components of RequiredKeys

Since RequiredKeys and OptionalKeys differ only in the branching portion of the conditional type and share the same basic structure, let's look at how RequiredKeys is constructed.

RequiredKeys is composed of a combination of the following:

  • {} type and never type
  • Pick type (utility type)
  • Index access types
  • Conditional Types
  • Mapped Types and mapping modifiers (mapping modifier)

{} Type

The {} type is an object type with no properties, and values except null and undefined can be assigned to variables of type {}.

An important property of the {} type in the custom types we are discussing is that the {} type does not become a subtype of an object type that has even one required property.
In other words, the {} type cannot be assigned to a variable of an object type that has required properties.

On the other hand, the {} type is a subtype of object types that have only optional properties.

type OptionalOnly = { a?: string; b?: number };

type RequiredOnly = { a: string; b: number };


const x: OptionalOnly = {}; // OK

const y: RequiredOnly = {}; // Type Error
//Type '{}' is missing the following properties from type 'RequiredOnly': a, bts(2739)

never Type

Additionally, no value can be assigned to a variable of the never type.
When the never type is used in a union with other types, the never part disappears from the union.

For example, the string | never type becomes the string type.
The never type is like an empty set; taking a union with another set does not change the result.

https://zenn.dev/axoloto210/articles/advent-calender-2023-day10

Pick Type

The Pick type allows you to create an object type by specifying an object type Type and a union of string literal types Keys representing the object's property keys, as in Pick<Type, Keys>.

type PickedBaseObj = {
    pickedString: string
    pickedNumber: number
    other: string
}

type PickedObj = Pick<PickedBaseObj, 'pickedString'|'pickedNumber'>
//   ^? type PickedObj = {
//          pickedString: string;
//          pickedNumber: number;
//      }

https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys

Index Access Types

By using index access types, you can extract the type of a property from an object type.
You retrieve the property type by specifying a key, much like indexing into an array or object.

If you specify a union of string literals, you can extract the property types in the form of a union type.

type IndexedAccessBaseObj = {
    indexedString: string
    indexedNumber: number
    other: number
}

type IndexedAccessObj = IndexedAccessBaseObj['indexedString' | 'indexedNumber']
//   ^? type IndexedAccessObj = string | number

Conditional Types

Conditional types are formed by combining extends with a notation similar to a ternary operator (? :), as in T extends string ? number : boolean. In this example, if T is a subtype of string, it results in the number type following the ?; otherwise, it results in the boolean type following the :.

type Conditional<T> = T extends string ? number : boolean

type ConditionalString = Conditional<string>
//   ^? type ConditionalString = number
type ConditionalNumber = Conditional<number>
//   ^? type ConditionalNumber = boolean

Mapped Types and Mapping Modifiers (mapping modifier)

By using mapped types, you can create a new object type from an existing one. You can map property keys of an object to another object type.

For example, in the following instance, you get an object type where all properties are of type boolean from the object type passed as Type.

type OptionsFlags<Type> = {
  [Property in keyof Type]: boolean;
};

https://www.typescriptlang.org/docs/handbook/2/mapped-types.html

Also, by using mapping modifiers, you can add or remove readonly or ? (whether it is an optional property).

By specifying -?, you can make a property required.

type MappedBaseType = {
  foo?: string;
  bar?: number;
};

type RequiredMappedType = {
  [K in keyof MappedBaseType]-?: MappedBaseType[K];
};
// type RequiredMappedType = {
//   foo: string;
//   bar: number;
// }

keyof MappedBaseType results in "foo" | "bar".
For each of these "foo" and "bar", you can think of it as adding/removing modifiers or specifying the property type.

{
    "foo": MappedBaseType["foo"] // Remove ? from foo?.
    "bar": MappedBaseType["bar"] // Remove ? from bar?.
}

https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#mapping-modifiers

How RequiredKeys Works

Let's look at the structure of RequiredKeys again.

type RequiredKeys<T> = {
  [K in keyof T]-?: {} extends Pick<T, K> ? never : K
}[keyof T]

RequiredKeys creates an object type using a mapped type { [K in keyof T]-?: {} extends Pick<T, K> ? never : K } and then retrieves a union of property types via index access [keyof T].

Looking closer at the mapped type part:
In the [K in keyof T]-? part, all optional properties are converted to required properties when creating a new object type from the object type T.

Next, let's examine the conditional type part: {} extends Pick<T, K> ? never : K.
Pick<T, K> extracts the property type of T for the property key K.

If {} is a subtype of Pick<T, K>, the type of the property corresponding to the key K in the mapped type becomes never; otherwise, it becomes the key K itself.

The fact that {} is a subtype of Pick<T, K> means that a value of type {} can be assigned to a variable of type Pick<T, K>.
When K is the key of an optional property, Pick<T, K> becomes an object type with one optional property, like {foo?: number}.
Since {} is an object type with no properties, it can be assigned to any object that contains only optional properties.

Through {} extends Pick<T, K> ? never : K, we ensure that for required properties of T, the value is the property key itself, while for optional properties of T, the value type becomes never.

The object type created by the mapped type looks like the commented-out section below:

type RequiredObj<T> = {
  [K in keyof T]-?: {} extends Pick<T, K> ? never : K;
};

type MappedObj = RequiredObj<Obj>;
// type MappedObj = {
//     requiredString: "requiredString";
//     requiredObject: "requiredObject";
//     optionalString: never;
//     optionalObject: never;
//     requiredUndefinedOrNumber: "requiredUndefinedOrNumber";
//     optionalUndefinedOrNumber: never;
// }

If -? were not specified, the never parts would become undefined, and retrieving the index access type with [keyof T] would result in a union type that includes undefined.
(Remember that in a union with never, the never part disappears.)

By performing index access with the union of property keys keyof T on this mapped type, we obtain a union of the required property keys and never.

Since never disappears when unioned, we finally get only the keys of the required properties.

Conclusion

We have explored the custom utility types used in the internal implementation of Next.js (though these types are used beyond just Next.js).
Practical custom utility types were built using combinations of features commonly used for type manipulation, such as mapped types and conditional types.
When so many features are combined, you can really appreciate the value of having them encapsulated as custom utility types.

Understanding how these types work will surely broaden the scope of type manipulations you can read and use.

GitHubで編集を提案

Discussion