Lesson 4 of 11 · 9 min

Objects and interfaces

An interface describes the shape of an object: which properties it has and their types.

interface Product {
  name: string;
  price: number;
  inStock: boolean;
}

const pen: Product = { name: "Pen", price: 1.2, inStock: true };
const bad: Product = { name: "Pen" };
// error: properties 'price' and 'inStock' are missing

Functions can take and return interfaces, and TypeScript checks every use:

function label(p: Product): string {
  return `${p.name} - ${p.price}`;
}

Optional and read-only properties

  • ? marks a property that may be missing: email?: string. Its type includes undefined, so check it before use.
  • readonly means it can be set when the object is created, but not changed afterwards.
interface User {
  readonly id: number;
  name: string;
  nickname?: string;
}

const u: User = { id: 1, name: "Ana" };
u.name = "Anna";   // fine
u.id = 2;          // error: cannot assign to 'id' because it is read-only

Interfaces can also extend each other: interface Teacher extends User { subject: string }.

Your task

  1. Define interface Student with a read-only id (number), name (string), age (number) and an optional email (string).
  2. Fix the starter's objects and code so there are no type errors.
  3. Write describe(s: Student): string returning "Ana (21)", or "Tino (19) <t@x.com>" when there is an email.
main.ts
// Define interface Student here


const ana: Student = { id: 1, name: "Ana" };
const tino: Student = { id: 2, name: "Tino", age: 19, email: "t@x.com" };
tino.id = 3;

function describe(s: Student): string {
  return "";
}

console.log(describe(ana));
console.log(describe(tino));

TypeScript 5.9 runs right here in your browser. The first run downloads about 1.5 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…