TypeScriptLesson 5 of 16
Objects and interfaces
An interface describes the shape of an object: which fields it has and what types they are. Any object declared with that type has to match it.
Key points
- interface User { id: number; name: string } is a name plus a list of fields.
- A ? makes a field optional: email?: string.
- extends adds fields to an existing interface.
- Forget a required field and TypeScript tells you which one.
Example
interface User { id: number; name: string; email?: string; // optional property} interface Admin extends User { permissions: string[];} const anna: User = { id: 1, name: "Anna" };const ben: Admin = { id: 2, name: "Ben", email: "ben@example.com", permissions: ["edit"] };// const ghost: User = { id: 3 }; // error: property 'name' is missing function contact(user: User): string { return user.email ?? "no email";} console.log(`${anna.name}: ${contact(anna)}`);console.log(`${ben.name}: ${contact(ben)}, can ${ben.permissions.join(", ")}`);Admin gets every field of User and adds permissions. An object without name fails the check, and a missing email is replaced with text through ??.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.Extend CartItem with quantity and an optional gift flag, make lineTotal return price times quantity, and print "Mug: 16 (gift)" and "Tea: 15".
Output
What your program prints appears here.