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 includesundefined, so check it before use.readonlymeans 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
- Define
interface Studentwith a read-onlyid(number),name(string),age(number) and an optionalemail(string). - Fix the starter's objects and code so there are no type errors.
- Write
describe(s: Student): stringreturning"Ana (21)", or"Tino (19) <t@x.com>"when there is an email.