Interfaces: Describing an Object Shape
An interface is a blueprint that says exactly what properties an object must have.
What you will learn
- Define an object shape with an interface
- Use an interface to type a variable and a function parameter
- See an error when a property is missing or wrong
A blueprint for objects
Objects in JavaScript can have any shape, which is flexible but risky. An interface describes the exact shape an object should have — which properties it needs and the type of each.
interface User {
name: string;
age: number;
isAdmin: boolean;
}Note: Output: (No output — an interface is a description only. It disappears when compiled to JavaScript; it exists just to check your code.)
Use it to type an object
Now any variable typed as User must match that shape exactly:
interface User {
name: string;
age: number;
isAdmin: boolean;
}
const asha: User = {
name: 'Asha',
age: 21,
isAdmin: false
};
console.log(asha.name + ' is ' + asha.age);Note: Output:
Asha is 21
The object has all three required properties with the right types, so TypeScript is happy. Editors will also autocomplete asha. for you.
Missing or wrong properties are caught
interface User {
name: string;
age: number;
isAdmin: boolean;
}
const ben: User = {
name: 'Ben',
age: 'twenty' // wrong type, and isAdmin is missing
};Note: Output: Error: Type 'string' is not assignable to type 'number' (age). Error: Property 'isAdmin' is missing in type ... The interface guarantees every User has the right properties with the right types. Both mistakes are flagged.
Interfaces type function parameters too
A common, powerful use: type the object a function expects.
interface User {
name: string;
age: number;
isAdmin: boolean;
}
function welcome(user: User): string {
return 'Welcome, ' + user.name;
}
console.log(welcome({ name: 'Asha', age: 21, isAdmin: true }));Note: Output:
Welcome, Asha
The function will only accept an object with the complete User shape, so user.name is guaranteed to exist.
Tip: Name interfaces with a capital letter (User, Product, Order). Think of an interface as a contract: "any object claiming to be a User must look like this".
Q. What does an interface describe?
✍️ Practice
- Write a
Productinterface withtitle: string,price: numberandinStock: boolean, then make a matching object. - Write a function that takes a
Productand returns its title; try passing an object missingprice.
🏠 Homework
- Design a
Bookinterface (title, author, pages, available) and create two book objects that satisfy it.