Search⌘ K

Custom Mapped Type

Explore creating custom mapped types in TypeScript to improve your code efficiency. Understand how to enforce non-nullable types, use conditional properties based on existing fields, and apply type constraints that prevent compilation errors. This lesson guides you through practical examples to master advanced type mapping techniques.

Creating a “NonNullable” type

The first custom type shows how to use never to tell TypeScript to not compile if a custom map is not respected. The code map is a generic variable that is neither undefined nor null. In the case that the value is either one, TypeScript does not compile.

TypeScript 3.3.4
type NoNullValue<T> = T extends null | undefined
? never
: T;
function print<T>(p: NoNullValue<T>): void {
console.log(p);
}
print("Test"); // Compile
// print(null); // Does not compile

Creating a custom mapping requires ...