Arrays and Objects · TypeScript

Ch 2 · The Types You Will Use Every Day — card 2 of 5.

An array type is written as the element type followed by []. An object type is written by listing its properties. Once TypeScript knows the shape, it will catch a misspelt property name, a missing field, and a value of the wrong kind — the three mistakes that account for most of the time you have spent staring at undefined.

const rates: number[] = [1500, 2200, 3000];
const clients: string[] = ["Rehman Textiles", "Sana Foods"];

const job: { title: string; days: number; paid: boolean } = {
  title: "Landing page",
  days: 4,
  paid: false
};

console.log(clients[0] + " / " + job.title);
console.log("average rate: " + rates.reduce((a, b) => a + b, 0) / rates.length);

That inline object type is correct but ugly, and you would not want to repeat it in five places. Chapter 3 gives it a name. For now, notice what it buys you: write job.tittle and the compiler stops you, instead of Node handing you undefined and letting it flow into a template string as the word "undefined" on a client's screen.