Typescript’s keyof is pretty neat!
Typescript’s keyof
keyword is a powerful feature that allows developers to create type-safe code when working with object keys. It is one of the many useful features that Typescript provides to make JavaScript development more robust and maintainable.
When working with objects in JavaScript, it is common to access and manipulate their properties using string keys. For example, we might have an object representing a person with properties like name
, age
, and email
. Without Typescript, we would have to rely on string literal types to ensure that our code is type-safe. However, with keyof
, we can define types that represent the keys of an object and utilize them in a type-safe manner.
Here’s an example of how keyof
can be used in Typescript:
type Person = {
name: string;
age: number;
email: string;
}
function getProperty(obj: Person, key: keyof Person) {
return obj[key];
}
const person: Person = {
name: 'John Doe',
age: 30,
email: 'john.doe@example.com',
}
const name = getProperty(person, 'name'); // type of name is string
const age = getProperty(person, 'age'); // type of age is number
const email = getProperty(person, 'email'); // type of email is string
const invalidProperty = getProperty(person, 'address'); // Error: 'address' does not exist on type 'Person'
In the example above, the keyof Person
type allows us to pass any valid key of the Person
object to the getProperty
function. This makes our code more predictable and less error-prone, as it enforces type safety at compile-time and prevents us from accessing properties that don’t exist on the object.
Overall, Typescript’s keyof
feature is pretty neat and can be incredibly useful for creating type-safe code when working with objects. It is just one of the many reasons why Typescript is becoming increasingly popular among JavaScript developers.