DEV Community

Cover image for Using Typescript Generic Constraints to Restrict Function Arguments Based on Other Arguments
Nick Scialli (he/him)
Nick Scialli (he/him)

Posted on

Using Typescript Generic Constraints to Restrict Function Arguments Based on Other Arguments

Typescript Generics can be used in functions to constrain the types of other arguments provided to the same function. Let's explore this idea!

A simple use case

Let's say we want to create a function that sets the key of an object. A fairly simple task; we might write is in JavaScript as follows:

function setObjectKey(obj, key, value) {
  obj[key] = value;
}

Then, in practice, we might use it like this:

const person = {
  name: "Jorge",
  age: 22
}

setObjectKey(person, age, 23);

In doing so, we set the age property on the person object to the value 11.

Doing this with type safety

So how can we achieve type safety when performing this operation? Using Generics!

Using Generics, we'll specify that our object is of type O, the key is of type K, and the value must be of type O[K].

function setObjectKey<O, k extends keyof O>(obj: O, key: K, value: O[K]) {
  obj[key] = value;
}

Now, when we try to violate the type of a particular key, our Typescript compiler yells at us!

Typescript lint warnings

Hooray for failing faster with Typescript!

Top comments (0)