In TypeScript, both interface and type help you define the shape of objects. While they can often be used in similar ways, there are a few important differences to know.
interfaceusesextendsto inherit:
interfaceAnimal{name: string;}interfaceDogextendsAnimal{breed: string;}typeuses&to combine types:
typeAnimal={name: string;};typeDog=Animal&{breed: string;};interfacesupports merging. You can define it more than once, and TypeScript will combine the definitions:
interfaceUser{name: string;}interfaceUser{age: number;}// User = { name: string; age: number }typedoes not support merging. Declaring the same type twice causes an error.
- Use
interfacewhen you're defining object shapes, especially with classes or APIs. - Use
typewhen you need to create unions, intersections, or advanced types like tuples and conditional types.
There’s no strict rule, but:
- Prefer
interfacefor objects and class shapes. - Use
typewhen you need more flexibility or are working with non-object types.
If you're new to TypeScript, you might have come across the keyof keyword and wondered what it does. Let me explain it to you in simple terms.
In TypeScript, keyof is used to get the type of the keys of an object. It returns a union type of all the keys in a given type, making your code safer and more flexible.
Let’s say you have an interface Person:
interfacePerson{name: string;age: number;}typePersonKeys=keyofPerson;// "name" | "age"In this case, keyof Person will give you a union type of the keys—"name" and "age".
You can use keyof to create functions that dynamically access object properties, ensuring type safety:
interfaceProduct{id: number;name: string;}functiongetProperty<T>(obj: T,key: keyofT){returnobj[key];}constproduct={id: 1,name: "Laptop"};console.log(getProperty(product,"name"));// Output: "Laptop"Here, the key parameter is guaranteed to be a valid key of Product, so you can't accidentally pass an invalid property.
The keyof keyword in TypeScript helps you work with object keys in a type-safe way, making your code more reliable and easier to maintain. It ensures that you can only access valid keys from an object, preventing runtime errors.