Higher-Order Types in TypeScript
Last Updated :
26 Sep, 2024
Higher-order types are among the advanced aspects of Typescript that give priority to types as first-class citizens, similar to higher-order functions of JavaScript that accept a function as an argument or return a function, higher-order types can accept types or return types.
These are the following topics that we are going to discuss:
What Are Higher-Order Types?
A higher-order type is defined as a type that satisfies any of the conditions-
- Accepts one or more types as parameters.
- It returns a new type based on the input type.
Higher order types can be referred to as meta types whereby the meta type is defined by other types, they are also particularly useful in making such generic type utilities that can work with types in ways even more complex than just simple manipulation, a higher order type is a functional type in the sense that it couples functions and types, Generic types can accept parameters where these parameters are also their types that go ahead to output different types, this is mostly similar to the higher order functions in which a function accepts a function or an argument and returns a function.
Why Use Higher-Order Types?
Higher-order types are useful when:
- You need to create a reusable and flexible type that can work across different contexts.
- You want to compose multiple types to build more complex ones.
- You are working with complex data structures such as deeply nested objects or recursive structures and you need a way to create dynamic type transformations.
Understanding Higher-Order Types
Higher-order types normally include TypeScript generics, mapped types, and conditional types together, let‘s appreciate all the components:
- Generics: Enforce parameters to be supplied to the types in the same way as how one can supply arguments to a function.
- Mapped Types: Construct types by visiting the properties of an existing type and scrolling through the properties.
- Conditional Types: Reassigning a condition gives a different effect/purpose on a type and then returns the type conditionally.
By putting such effects together, the higher-order types become efficient.
Methods of Higher-Order Types
Simple Higher-Order Type
We’ll create a higher-order type IdentityType, which simply takes a type T as a parameter and returns it as it is.
Example: In this simple example, IdentityType accepts any type and returns that type, it's similar to a higher-order function that returns the input unchanged.
JavaScript
type IdentityType<T> = T;
type StringType = IdentityType<string>;
type NumberType = IdentityType<number>;
// Example usage:
const name: StringType = "Pankaj";
const age: NumberType = 20;
console.log(name);
// Output: "Pankaj"
console.log(age);
// Output: 20
Output:
Pankaj
20
Higher-Order Type for Wrapping in an Array
Now we will introduce the higher-order type called WrapInArray which can be understood that whatever type is given an array of that type is returned WrapInArray is a higher-order type that takes a type and puts it into an array this type is generic since it can be used for any type T.
Example: In this example, we will use the Higher-Order Type for Wrapping in an Array
JavaScript
type WrapInArray<T> = T[];
// Higher-order type
type StringArray = WrapInArray<string>;
type NumberArray = WrapInArray<number>;
// Example usage:
const strings: StringArray = ["one", "two", "three"];
const numbers: NumberArray = [1, 2, 3];
console.log(strings);
// Output: ["one", "two", "three"]
console.log(numbers);
// Output: [1, 2, 3]
Output:
[ 'one', 'two', 'three' ]
[ 1, 2, 3 ]
Recursive Higher-Order Type
Here we’ll create a recursive higher-order type DeepReadonly, which makes all properties of a given type T and its nested objects read-only, DeepReadonly is a recursive higher-order type that applies the read-only modifier to every property in the object, including nested objects, makes the entire object deeply immutable.
Example: In this example we will use the Recursive Higher-Order Type
JavaScript
type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P];
};
interface Example {
a: number;
b: string;
c: {
d: boolean;
e: {
f: string;
};
};
}
type ReadonlyExample = DeepReadonly<Example>;
// Example usage:
const example: ReadonlyExample = {
a: 42,
b: "Hello",
c: {
d: true,
e: {
f: "world",
},
},
};
// example.a = 10;
// Error: Cannot assign to 'a' because it is a read-only property.
console.log(example);
Output:
{ a: 42, b: 'Hello', c: { d: true, e: { f: 'world' } } }
Higher-Order Type for Conditional Mapping
Here we'll create a higher-order type Nullable that converts all properties of a given type to be nullable (T | null), Nullable is a higher-order type that converts each property of a given type T to be nullable and this allows us to create types where each field can be null or the original type.
Example: In this example we will use the Higher-Order Type for Conditional Mapping
JavaScript
type Nullable<T> = {
[P in keyof T]: T[P] | null;
};
interface User {
name: string;
age: number;
address: string;
}
type NullableUser = Nullable<User>;
// Example usage:
const user: NullableUser = {
name: null,
age: 20,
address: null,
};
console.log(user);
Output:
{ name: null, age: 20, address: null }
Higher-Order Type for Function Wrapping
Now we will look for a higher-order type FunctionWrapper which will take a function as an argument and provide more arguments to that function, here, FunctionWrapper is a high-order type that uses a functional type T and attaches a string argument to the functional type, this kind of type is helpful in partially replacing or completely trashing a function.
Example: In this example we will use the Higher-Order Type for Function Wrapping
JavaScript
type FunctionWrapper<T extends (...args: any[]) => any> =
(...args: [...Parameters<T>, string]) => ReturnType<T>;
function greet(name: string): string {
return `Hello, ${name}!`;
}
const wrappedGreet: FunctionWrapper<typeof greet> = (name, suffix) => {
return greet(name) + suffix;
};
// Example usage:
console.log(wrappedGreet("Pankaj", "!!!"));
Output:
Hello, Pankaj!!!!
Limitations
As much as higher-order types are wieldy when it comes to abstraction, they certainly have their negatives.
- Complexity: Higher-order types are not easy to grasp and are prone to misuse especially when mixed with recursive or conditional types.
- Inference Issues: There are cases when it appears almost impossible to utilize a TypeScript type inference system with nested or recursive higher-order types.
- Performance: The use of advanced higher-order types tends to impair the performance of the compiler within big code bases.
Conclusion
Higher-order types in TypeScript are a great asset that allows the creation of reusable and flexible type utilities, you can come up with type transformations that allow your code to be safer, easier to change and maintain while treating types as entities instead of entities that have change being an afterthought, in this article, we covered multiple cases studies on higher-order types, starting from simple identity type systems to rather complex structure like DeepReadonly where we also had recursive types.
Similar Reads
TypeScript Generic Types
TypeScript Generic Types can be used by programmers when they need to create reusable components because they are used to create components that work with various data types and this provides type safety. The reusable components can be classes, functions, and interfaces. TypeScript generics can be u
2 min read
TypeScript Generic Object Types
TypeScript Generic Object Types allow you to create flexible and reusable type definitions for objects. These generic types can work with different shapes of objects while providing type safety, ensuring your code is both robust and adaptable. They are particularly useful for creating functions or c
3 min read
Opaque Types In TypeScript
In TypeScript Opaque types concept allows for the definition of specialized types such as strings or numbers which are derived from primitive types but do not have the characteristics of the base types, the purpose of this is to prevent specific actions regarding the type in question, or to make thi
4 min read
How to Check Types in Typescript?
Checking types in TypeScript involves methods like typeof for primitive types, instanceof for class instances, and custom type guards for complex type validation. These techniques help ensure variables are correctly typed, improving code safety, and readability, and preventing runtime errors.Here ar
3 min read
TypeScript Object Intersection Types
In TypeScript, Object Intersection Types are a way to create new types by combining multiple types into a single type. This is done using the & (ampersand) operator. Intersection types allow you to express that an object must have all the properties and methods of each type in the intersection. This
3 min read
TypeScript Indexed Access Types
TypeScript's Indexed Access Types allow you to access the type of a specific property within an object or array using bracket notation (Type[Key]). This feature provides precise type information about properties or elements, enhancing type safety when accessing deeply nested structures or specific o
3 min read
Data types in TypeScript
In TypeScript, a data type defines the kind of values a variable can hold, ensuring type safety and enhancing code clarity. Primitive Types: Basic types like number, string, boolean, null, undefined, and symbol.Object Types: Complex structures including arrays, classes, interfaces, and functions.Pri
3 min read
TypeScript Literal Inference Type
TypeScript Literal Inference Type allows you to create type annotations based on actual values, variables, or constants. This enhances type safety and code clarity by specifying that a variable can only hold specific, exact values. It's a way to express the precise values that a variable can take on
2 min read
TypeScript Object Extending Types
TypeScript Object Extending Types refers to the ability to create new object types or interfaces that inherit properties and methods from existing ones using the extends keyword. This allows developers to build more complex, reusable, and maintainable type definitions by composing simpler types. Syn
3 min read
TypeScript Literal Types
TypeScript's literal types allow developers to specify exact values for variables, function parameters, or properties, enhancing type safety by ensuring variables can only hold predefined values. Allow variables to have specific, exact values.Enhance code reliability by restricting permissible value
3 min read