TypeScript
/Beginner
Interface Basics
Definition
An interface is a syntax in TypeScript used to define the shape of an object. It explicitly names a specific combination of properties and their types.
Explain Like I'm New
An interface is a contract. If a component says 'I need a User object', the Interface is the document that lists exactly what makes an object a 'User'. If your object doesn't match the contract (e.g., missing an email), it gets rejected.
Real World Example
Defining the props for a React component: `interface ButtonProps { label: string; onClick: () => void; }`.
Common Use Cases
- •Defining object shapes
- •Object-oriented programming (implements)
Interactive Example
// Defining the contract interface Product { id: number; name: string; price: number; description?: string; // Optional } // Fulfilling the contract const myLaptop: Product = { id: 101, name: "MacBook Pro", price: 1999 }; function printLabel(item: Product) { console.log(`Item: ${item.name} - $${item.price}`); }
Interview Questions
basic
- Can an interface define a function type?
intermediate
- Can you add properties to an interface after it is defined?
advanced
- What is the difference between an Interface and a Type Alias?