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 Tutorial TypeScript is a superset of JavaScript that adds extra features like static typing, interfaces, enums, and more. Essentially, TypeScript is JavaScript with additional syntax for defining types, making it a powerful tool for building scalable and maintainable applications.Static typing allows you to
8 min read
TypeScript Basics
Introduction to TypeScriptTypeScript is a syntactic superset of JavaScript that adds optional static typing, making it easier to write and maintain large-scale applications.Allows developers to catch errors during development rather than at runtime, improving code reliability.Enhances code readability and maintainability wit
5 min read
Difference between TypeScript and JavaScriptEver wondered about the difference between JavaScript and TypeScript? If you're into web development, knowing these two languages is super important. They might seem alike, but they're actually pretty different and can affect how you code and build stuff online.In this article, we'll break down the
4 min read
How to install TypeScript ?TypeScript is a powerful language that enhances JavaScript by adding static type checking, enabling developers to catch errors during development rather than at runtime. As a strict superset of JavaScript, TypeScript allows you to write plain JavaScript with optional extra features. This guide will
3 min read
Hello World in TypeScriptTypeScript is an open-source programming language. It is developed and maintained by Microsoft. TypeScript follows javascript syntactically but adds more features to it. It is a superset of javascript. The diagram below depicts the relationship:Typescript is purely object-oriented with features like
3 min read
How to execute TypeScript file using command line?TypeScript is a statically-typed superset of JavaScript that adds optional type annotations and compiles to plain JavaScript. It helps catch errors during development. To execute a TypeScript file from the command line, compile it using tsc filename.ts, then run the output JavaScript file with node.
2 min read
Variables in TypeScriptIn TypeScript, variables are used to store values that can be referenced and manipulated throughout your code. TypeScript offers three main ways to declare variables: let, const, and var. Each has different behavior when it comes to reassigning values and scoping, allowing us to write more reliable
6 min read
What are the different keywords to declare variables in TypeScript ?Typescript variable declarations are similar to Javascript. Each keyword has a specific scope. Let's learn about variable declarations in this article. In Typescript variables can be declared by using the following keywords:varlet constVar keyword: Declaring a variable using the var keyword.var vari
4 min read
Identifiers and Keywords in TypeScriptIn TypeScript, identifiers are names used for variables, classes, or methods and must follow specific naming rules. Keywords are reserved words with predefined meanings and cannot be used as identifiers. Comments, both single-line and multi-line, enhance code readability and are ignored during code
2 min read
TypeScript primitive types
Data types in TypeScriptIn 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.Prim
3 min read
TypeScript NumbersTypeScript Numbers refer to the numerical data type in TypeScript, encompassing integers and floating-point values. The Number class in TypeScript provides methods and properties for manipulating these values, allowing for precise arithmetic operations and formatting, enhancing JavaScript's native n
4 min read
TypeScript StringIn TypeScript, the string is sequence of char values and also considered as an object. It is a type of primitive data type that is used to store text data. The string values are used between single quotation marks or double quotation marks, and also array of characters works same as a string. TypeSc
4 min read
Explain the concept of null and its uses in TypeScriptNull refers to a value that is either empty or a value that doesn't exist. It's on purpose that there's no value here. TypeScript does not make a variable null by default. By default unassigned variables or variables which are declared without being initialized are 'undefined'. To make a variable nu
3 min read
TypeScript Object types
What are TypeScript Interfaces?TypeScript interfaces define the structure of objects by specifying property types and method signatures, ensuring consistent shapes and enhancing code clarity.Allow for optional and read-only properties for flexibility and immutability.Enable interface inheritance to create reusable and extendable
4 min read
TypeScript classA TypeScript class is a blueprint for creating objects, encapsulating properties (data) and methods (behavior) to promote organization, reusability, and readability.Supports inheritance, allowing one class to extend another and reuse functionality.Provides access modifiers (public, private, protecte
4 min read
How enums works in TypeScript ?In this article, we will try to understand all the facts which are associated with enums in TypeScript. TypeScript enum: TypeScript enums allow us to define or declare a set of named constants i.e. a collection of related values which could either be in the form of a string or number or any other da
4 min read
TypeScript TuplesIn JavaScript, arrays consist of values of the same type, but sometimes we need to store a collection of values of different types in a single variable. TypeScript offers tuples for this purpose. Tuples are similar to structures in C programming and can be passed as parameters in function calls.Tupl
3 min read
TypeScript other types
What is any type, and when to use it in TypeScript ?Any is a data type in TypeScript. Any type is used when we deal with third-party programs and expect any variable but we don't know the exact type of variable. Any data type is used because it helps in opt-in and opt-out of type checking during compilation. In this article, we will see what is any
3 min read
How to Create an Object in TypeScript?TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data.Creating Objects in TypescriptNow, let
4 min read
What is an unknown type and when to use it in TypeScript ?In Typescript, any value can be assigned to unknown, but without a type assertion, unknown can't be assigned to anything but itself and any. Similarly, no operations on an unknown are allowed without first asserting or restricting it down to a more precise type. Â similar to any, we can assign any va
3 min read
Explain the purpose of never type in TypeScriptIn Typescript when we are certain that a particular situation will never happen, we use the never type. For example, suppose you construct a function that never returns or always throws an exception then we can use the never type on that function. Never is a new type in TypeScript that denotes value
3 min read
TypeScript combining types
TypeScript Assertions
TypeScript Functions
TypeScript interfaces and aliases
TypeScript classes
How to Extend an Interface from a class in TypeScript ?In this article, we will try to understand how we to extend an interface from a class in TypeScript with the help of certain coding examples. Let us first quickly understand how we can create a class as well as an interface in TypeScript using the following mentioned syntaxes: Syntax:Â This is the s
3 min read
How to Create an Object in TypeScript?TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data.Creating Objects in TypescriptNow, let
4 min read
How to use getters/setters in TypeScript ?In TypeScript, getters and setters provide controlled access to class properties, enhancing encapsulation and flexibility.Getters allow you to retrieve the value of a property with controlled logic.Setters enable controlled assignment to properties, often including validation or transformations.Java
5 min read
TypeScript InheritanceInheritance is a fundamental concept in object-oriented programming (OOP). It allows one class to inherit properties and methods from another class. The class that inherits is called the child class, and the class whose properties and methods are inherited is called the parent class. Inheritance ena
3 min read
When to use interfaces and when to use classes in TypeScript ?TypeScript supports object-oriented programming features like classes and interfaces etc. classes are the skeletons for the object. it encapsulates the data which is used in objects. Interfaces are just like types for classes in TypeScript. It is used for type checking. It only contains the declarat
4 min read
Generics Interface in typescript"A major part of software engineering is building components that not only have well-defined and consistent APIs but are also reusable. " This sentence is in the official documentation we would start with. There are languages that are strong in static typing & others that are weak in dynamic typ
5 min read
How to use property decorators in TypeScript ?Decorators are a way of wrapping an existing piece of code with desired values and functionality to create a new modified version of it. Currently, it is supported only for a class and its components as mentioned below: Class itselfClass MethodClass PropertyObject Accessor ( Getter And Setter ) Of C
4 min read