...

/

Using Generics to Constrain Types

Using Generics to Constrain Types

Learn how to use one generic type to apply a constraint on another type in TypeScript to improve type safety.

Construct a generic type from another

A generic type can be constructed out of another generic type. This technique essentially uses one type to apply a constraint on another type.

Let’s take a look at an example:

// Define a function named printProperty that takes two generic type parameters
function printProperty<T, K extends keyof T>
(object: T, key: K) {
let propertyValue = object[key];
console.log(`object[${key}] = ${propertyValue}`);
}
Generic function with constraint

Here, we have a function named printProperty that has two generic types named T and K.

The type K is constrained to be a value computed from the keyof operator on type T. Remember that the keyof operator will return a string literal type that is made up of the properties of an object, so K will be constrained to the property names of the type T.

The printProperty function has two parameters named object of type T, and key of type K. The function assigns the value of the object’s property named in the key parameter to a variable named propertyValue using the syntax object[key]. It then logs this value to the console.

Let’s test this function as follows:

index.ts
tsconfig.json
let obj1 = {
id: 1,
name: "myName",
print() { console.log(`${this.id}`) }
}
printProperty(obj1, "id");
printProperty(obj1, "name");
printProperty(obj1, "surname");
Using generic types
  • On lines 1–5, we have constructed an object named obj1, which has an id property of type number, a name property of type string, and a print function.

  • On lines 7–9, we call the printProperty ...