๐ŸŽ“ A1Learner
๐Ÿ”
0 of 33 lessons completed

TypeScript Interfaces

An interface names an object shape so the shape can be reused by name. Objects and parameters can then state that name in place of the full shape.

Name a shape with an interface

The interface lists the members once. The variable states the name as its type.

interface User {
  name: string;
  age: number;
}
const first: User = { name: "Ada", age: 36 };
console.log(first.name, first.age);

A missing member is refused

The User interface lists age as well as name. The object leaves age out.

interface User {
  name: string;
  age: number;
}
const first: User = { name: "Ada" };
console.log(first.name);

An interface as a parameter type

The parameter states the interface name. The function reads the members from the object it receives.

interface User {
  name: string;
  age: number;
}
function describe(user: User): string {
  return user.name + " is " + user.age + " years old";
}
console.log(describe({ name: "Mia", age: 31 }));

Example

interface Product {
  title: string;
  price: number;
}
const items: Product[] = [
  { title: "Notebook", price: 6 },
  { title: "Pen", price: 2 }
];
for (const item of items) {
  console.log(item.title + ": $" + item.price);
}

Key points

  • The interface keyword starts an interface declaration.
  • An interface names a shape once, and that name then works as a type.
  • An object assigned to an interface type must supply every member the interface lists.
  • An interface can state the type of a function parameter.
  • Two declarations with the same interface name merge into one interface.

In this example, the Product interface names a shape with a title and a price. The items array holds two objects that match that shape. The loop logs one line per object. Each line shows the title and the price of one product.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท TypeScript Playground

Exercise

What does an interface do?