TypeScript Course
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?

Flash Cards

Question

Can an interface define a function type?

Click to reveal answer
Answer

Yes. While usually used for objects, you can use an interface to define a function signature using an anonymous method signature: `interface MathFunc { (a: number, b: number): number }`.

Question

Can you add properties to an interface later?

Click to reveal answer
Answer

Yes! This is called 'Declaration Merging'. If you declare `interface User { name: string }` and later in the same file declare `interface User { age: number }`, TS merges them into one single interface containing both properties.