← Back tothis vs that

K keyof T vs K extends keyof T

Written byPhuoc Nguyen
Created
24 Aug, 2023
Category
TypeScript
One of the coolest features of TypeScript is the ability to limit the keys of an object to a specific subset of values using the `keyof` operator.
However, there are two similar-looking syntaxes for this operation that can be confusing for us: `K extends keyof T` and `K keyof T`. In this post, we'll explore the differences between these two syntaxes and when to use each one. Let's dive in!

K keyof T

The syntax `K keyof T` is a way to ensure that `K` is a key of the type `T`. It's an easy way to limit the type of a variable to a particular set of keys. For instance, let's take a look at the following code:
ts
interface Product {
color: string;
name: string;
size: 'small' | 'medium' | 'large' | 'extraLarge';
weight: number;
}

const getProperty = (item: Product, key: keyof Product): string | number => {
return item[key];
};

const item: Product = {
color: 'white',
name: 'T-Shirt',
size: 'medium',
weight: 200,
};
getProperty(item, 'color'); // `white`
getProperty(item, 'size'); // `medium`

// Argument of type '"length"' is not assignable
// to parameter of type 'keyof Product'.
getProperty(item, 'length'));
In this example, we have a function called `getProperty` that takes in an object of type `Product` and a key of type `keyof Product`. This means that the `key` parameter can only be set to `color`, `name`, `size` or `weight`, which are the only valid keys of the `Product` interface.
The cool thing is that TypeScript will give us an error at compile-time if we try to pass in an invalid key like `length`. This helps us catch errors early on and prevent bugs from popping up in our code.

K extends keyof T

The `K extends keyof T` syntax indicates that `K` must be a valid key of the `T` type. This syntax comes in handy when we need to accept multiple keys as input to a function or define a type that can have one of several key-value pairs. We can even use a union of keys with this syntax.
Let's take another look at the example we discussed earlier, but this time, let's leverage the benefits of this syntax.
ts
interface Product {
color: string;
name: string;
size: 'small' | 'medium' | 'large' | 'extraLarge';
weight: number;
}

const getProperty = <K extends keyof Product>(item: Product, keys: K[]): Product[K][] => {
return keys.map(key => item[key]);
};

const item: Product = {
color: 'white',
name: 'T-Shirt',
size: 'medium',
weight: 200,
};

getProperty(item, ['color']); // [`white`]
getProperty(item, ['size']); // [`medium`]
getProperty(item, ['color', 'size']); // [`white`, `medium`]

// Error: Type '"length"' is not assignable
// to type 'keyof Product'.
getProperty(item, ['length']));
In this example, we have a function called `getProperty`. It takes in an object of type `Person` and an array of keys, which can only be either `color`, `name`, `size` or `weight`. TypeScript makes sure we can't pass in any other keys.

In conclusion

To sum up, `K keyof T` specifies that `K` must be a single key of the type `T`, while `K extends keyof T` specifies that `K` must be a union of keys of the type `T`. Use `K keyof T` when you need to specify a single key, and use `K extends keyof T` when you need to allow multiple keys.
If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn