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

4 2

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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay