K keyof T vs K extends keyof T
Written byPhuoc Nguyen
Category
TypeScript
Created
24 Aug, 2023
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: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.
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.Questions? 🙋
Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.
Recent posts ⚡
Copy the content of an element to your clipboard
01 Oct, 2023
Make a text area fit its content automatically
30 Sep, 2023
Quickly insert alternate characters while typing
30 Sep, 2023
Zebra-like background
30 Sep, 2023
Add autocomplete to your text area
28 Sep, 2023
Linear scale of a number between two ranges
28 Sep, 2023
Highlight the current line in a text area
27 Sep, 2023
Create your own custom cursor in a text area
27 Sep, 2023
Mirror a text area for improving user experience
26 Sep, 2023
Display the line numbers in a text area
24 Sep, 2023
Select a given line in a text area
24 Sep, 2023
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