SyntaxPilot
Courses/JavaScript/Lesson 32
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

JavaScript · Lesson 32 of 40

TypeScript basics

queued

These are the notes for JavaScript episode 32. A restaurant bill program has three bugs, and JavaScript says nothing about any of them. A tip typed into a form arrives as the string "20", so withTip(280, "20") gives 28020. A typo, prcie instead of price, gives NaN. The program finishes with no error at all. So you'll invent static type checking: you write down once what kind of value each thing must be (a type), and a tool called tsc checks every line against those types before the code runs. That tool and language is TypeScript. You'll see why types can't go into a .js file (SyntaxError: Unexpected token ':'), how tsc finds both bugs with the exact line and a suggested fix, how types are erased when the code runs, and the basic toolkit: type inference, type and interface, optional properties, literal and union types, narrowing with typeof, why find() returns Dish | undefined, generics, and why unknown is safer than any. Every JavaScript output below is real Node.js 24 output (node main.js). Every TypeScript error is real output of TypeScript 5.9 (npx tsc --strict --noEmit main.ts). Long Node stack traces are cut after the first at lines.

Builds on: type coercion and + with strings (episode 3), template literals (4), arrays and find (7), objects (8), functions (9), destructuring and spread (12), try/catch (13), the quiz game (15), modules (18), JSON (19), toFixed and Math (20), tests and npm test (30). Leads to: the CLI to-do project (33), which uses all of this in one app.

The real-life idea: the railway reservation form

When you book a train ticket at the counter, you fill in a form. Every box says what kind of answer goes in: Name takes letters, Age takes a number, Gender takes one of a few fixed choices. The clerk checks the form at the counter, before the ticket is booked. If you wrote "twenty" in the Age box, the form comes straight back to you with that box marked. You don't find out when the train is already moving.

Railway reservation form TypeScript
A box on the form ("Age") a variable, parameter or property
What may go in the box ("a number") its type: age: number
A box with fixed choices (M / F / Other) a literal union of fixed choices: "veg" or "nonveg"
An optional box ("Email, if any") an optional property: email?: string
The clerk checking the form tsc, the type checker
Checked at the counter, before the train leaves checked before the program runs
The form sent back with the box marked a type error with the file, line and column
The ticket printed after the check the plain .js file tsc writes

The problem: three silent bugs

billTotal adds price * qty for every item (with reduce, episode 11). withTip adds a tip. The tip comes from the tip box on the screen, and everything typed into a form arrives as a string:

function billTotal(items) {
  return items.reduce((total, item) => total + item.price * item.qty, 0);
}
function withTip(total, tip) {
  return total + tip;
}
const cart = [
  { name: "Masala dosa", price: 120, qty: 2 },
  { name: "Filter coffee", price: 40, qty: 1 },
];
console.log(billTotal(cart));
const tip = "20";   // typed into the tip box
console.log(withTip(billTotal(cart), tip));
console.log(billTotal([{ name: "Idli", prcie: 30, qty: 2 }]));
280
28020
NaN
  • 280 is right.
  • 28020: + with a string joins text, it doesn't add (episode 3). 280 + "20" is "28020". A customer was just billed twenty-eight thousand rupees.
  • NaN: prcie is a typo, so item.price is undefined, and undefined * 2 is NaN (Not a Number).
  • And no error. The program exits normally.

Why JavaScript stayed quiet

  • JavaScript is dynamically typed: it only finds out what kind of value tip holds while that line is actually running.
  • When it meets a number plus a string, it doesn't complain; it coerces (quietly converts) the number to a string.
  • A property that doesn't exist is just undefined, not an error.
  • Tests (episode 30) help, but only for the cases you thought of.

What we want is to write down once, "tip must be a number, items must have a price", and have a tool check every line against that before anything runs. That is static typing: types checked from the code itself, without running it.

Dynamic typing (JavaScript) Static typing (TypeScript)
When types are checked while running, line by line before running, the whole program
A wrong type quietly converted, or a crash later an error from tsc, with the line
Who finds the bug the user, at runtime you, while writing
Extra work none writing some type notes

Types are not JavaScript

First try: just write the types into main.js. After a colon: items is an array of Item, and billTotal returns a number:

function billTotal(items: Item[]): number {
  return items.reduce((total, item) => total + item.price * item.qty, 0);
}
console.log(billTotal([{ name: "Masala dosa", price: 120, qty: 2 }]));
main.js:1
function billTotal(items: Item[]): number {
                        ^

SyntaxError: Unexpected token ':'
    at wrapSafe (node:internal/modules/cjs/loader:1861:18)
    ...

Node doesn't understand it, because JavaScript has no syntax for types. If you also add a type Item = ... line at the top, the error changes to SyntaxError: Unexpected identifier 'Item', for the same reason. We need a language that is JavaScript plus types, and a checker that understands it.

What TypeScript is

  • TypeScript is JavaScript with type notes added. It's made by Microsoft, free and open source. TypeScript files end in .ts.
  • Every JavaScript program is already valid TypeScript. You add types where they help.
  • The TypeScript compiler is called tsc. It reads your .ts files and checks every line against the types, without running anything. If everything is fine, it writes plain .js files with the types removed.
  • Node (or a browser) then runs the .js.
main.ts  ──►  tsc (checks every line)  ──►  main.js (types removed)  ──►  node runs it

Types only exist before the program runs. At runtime it's plain JavaScript again. This is called type erasure.

The same bill, with types

type Item = { name: string; price: number; qty: number };

function billTotal(items: Item[]): number {
  return items.reduce((t, item) => t + item.price * item.qty, 0);
}
function withTip(total: number, tip: number): number {
  return total + tip;
}
const cart: Item[] = [
  { name: "Masala dosa", price: 120, qty: 2 },
  { name: "Filter coffee", price: 40, qty: 1 },
];
console.log(billTotal(cart));
const tip = "20";
console.log(withTip(billTotal(cart), tip));
console.log(billTotal([{ name: "Idli", prcie: 30, qty: 2 }]));
  • type Item = { ... } gives a name to an object shape (a type alias).
  • items: Item[] is a type annotation: the parameter must be an array of Item.
  • ): number after the brackets is the return type.

Check it (--noEmit = check only, don't write any .js):

$ npx tsc --noEmit main.ts
main.ts(15,38): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
main.ts(16,40): error TS2561: Object literal may only specify known properties, but 'prcie' does not exist in type 'Item'. Did you mean to write 'price'?

How to read an error: main.ts(15,38) is the file, line 15, column 38. TS2345 is the error's code (you can search for it). Then the reason in plain English. Both bugs are found, and nothing ran. The second one even suggests the fix.

Fix both lines (const tip = Number("20"); and price: 30), and tsc prints nothing, which means no errors. Running it:

280
300
60

What tsc writes: types are erased

Run plain npx tsc main.ts (no --noEmit) on this file:

type Item = { name: string; price: number; qty: number };

function billTotal(items: Item[]): number {
  return items.reduce((t, item) =>
    t + item.price * item.qty, 0);
}

and it writes this main.js:

"use strict";
function billTotal(items) {
    return items.reduce((t, item) => t + item.price * item.qty, 0);
}

The type line is gone, the : Item[] and : number are gone. It's the JavaScript you'd write by hand ("use strict" comes from strict mode; tsc also re-formats the code).

node main.ts runs TypeScript, but does not check it

Node 24 can run a .ts file directly: node main.ts. It strips the types and runs the rest. It does not check them. On the buggy version above:

$ node main.ts
280
28020
NaN

Same wrong answers, no error. Checking is tsc's job. Run npx tsc --noEmit before you run or commit.

Type inference: you don't write every type

let tableNo = 5;        // TypeScript infers: number
tableNo = "five";

let waiter: string = "Ravi";   // or write it yourself
main.ts(2,1): error TS2322: Type 'string' is not assignable to type 'number'.

tableNo starts as 5, so TypeScript works out by itself that it's a number. That's type inference. You wrote no type and still got the check. Good practice: let TypeScript infer variables, and write types on function parameters (it can't guess those) and on objects you share.

The basic types

let dish: string = "Masala dosa";
let price: number = 120;
let isVeg: boolean = true;
let prices: number[] = [120, 60, 40];
let names: Array<string> = ["Dosa", "Idli"];
prices.push("50");
isVeg = "yes";
main.ts(6,13): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
main.ts(7,1): error TS2322: Type 'string' is not assignable to type 'boolean'.
Type Holds Example
string text "Masala dosa"
number any number (whole or decimal) 120, 40.5
boolean true or false true
number[] or Array<number> an array of numbers [120, 60]
undefined / null "no value" undefined
void a function returns nothing function log(): void

Function types

function gst(amount: number): number {
  return "Rs " + amount * 0.05;
}
function greet(name: string): void {
  console.log(`Hello, ${name}`);
}
greet();
main.ts(2,3): error TS2322: Type 'string' is not assignable to type 'number'.
main.ts(7,1): error TS2554: Expected 1 arguments, but got 0.

The return type is checked inside the function, and every call is checked against the parameters. In plain JavaScript, greet() would quietly print Hello, undefined.

Describing objects: type, optional properties and literal types

type FoodType = "veg" | "nonveg";
type Dish = {
  name: string;
  price: number;
  type: FoodType;
  spicy?: boolean;     // optional
};
const paneer: Dish = { name: "Paneer tikka", price: 220, type: "Veg" };
const dal: Dish = { name: "Dal makhani", price: 180 };
main.ts(8,58): error TS2820: Type '"Veg"' is not assignable to type 'FoodType'. Did you mean '"veg"'?
main.ts(9,7): error TS2741: Property 'type' is missing in type '{ name: string; price: number; }' but required in type 'Dish'.
  • "veg" as a type is a literal type: only that exact string is allowed.
  • | means or. "veg" | "nonveg" is a union of two literal types, like a form box with fixed choices.
  • spicy?: with a question mark is optional: it may be left out. Its type is then boolean | undefined.
  • A missing required property, or a wrong spelling of a choice, is caught. In JavaScript both would silently become wrong data on the menu.

interface: the other way to describe an object

interface Customer {
  readonly phone: string;
  name: string;
  email?: string;
}
const asha: Customer = { phone: "9876543210", name: "Asha" };
asha.name = "Asha Rao";
asha.phone = "9000000000";
console.log(asha.email.length);
main.ts(8,6): error TS2540: Cannot assign to 'phone' because it is a read-only property.
main.ts(9,13): error TS18048: 'asha.email' is possibly 'undefined'.
  • interface Customer { ... } does the same job as type Customer = { ... } for objects. Pick one style and stick to it.
  • readonly means the property can be set when the object is made, but never changed afterwards.
  • Changing name is fine; changing phone is an error. And because email is optional, TypeScript won't let you use .length without checking (more on this below). The safe way:
console.log(asha.email?.length);
console.log(asha.email ?? "no email");
undefined
no email
type interface
type Dish = { name: string } interface Dish { name: string }
can also name unions, like FoodType above only objects (and classes)
can't be re-opened can be extended later with another interface Dish
both: optional ?, readonly, used the same way

Union types and narrowing

A sneakier bug. formatPrice shows a price with two decimals using toFixed (episode 20):

function formatPrice(price) {
  return "Rs " + price.toFixed(2);
}
console.log(formatPrice(40));
console.log(formatPrice("40"));   // from a form
Rs 40.00
main.js:2
  return "Rs " + price.toFixed(2);
                       ^

TypeError: price.toFixed is not a function
    at formatPrice (main.js:2:24)
    ...

Strings don't have toFixed. JavaScript finds out only when a customer reaches that line.

In TypeScript, we're honest: the price can be a number or a string, a union type:

function formatPrice(price: number | string): string {
  return "Rs " + price.toFixed(2);
}
main.ts(2,24): error TS2339: Property 'toFixed' does not exist on type 'string | number'.
  Property 'toFixed' does not exist on type 'string'.

Same bug, found before running, with the exact reason. You may only use what every member of the union has.

The fix is to check first. After if (typeof price === "string") turns it into a number, TypeScript knows that from then on price must be a number:

function formatPrice(price: number | string): string {
  if (typeof price === "string") price = Number(price);
  return "Rs " + price.toFixed(2);   // here: number
}
console.log(formatPrice(40));
console.log(formatPrice("40"));
$ npx tsc --noEmit main.ts     (no errors)
$ node main.ts
Rs 40.00
Rs 40.00

This is narrowing: an if check makes a wide type (number | string) narrower (number) inside the code it guards. Checks TypeScript understands include typeof x === "string", x === undefined, if (x), "price" in x, x instanceof Error, and comparing a literal like status === "paid".

The undefined crash, caught before running

The most common crash in JavaScript. find (episode 7) looks for vada:

const menu = [
  { name: "Masala dosa", price: 120 },
  { name: "Idli", price: 60 },
];
const dish = menu.find((d) => d.name === "Vada");
console.log(dish.price);
main.js:6
console.log(dish.price);
                 ^

TypeError: Cannot read properties of undefined (reading 'price')
    at Object.<anonymous> (main.js:6:18)
    ...

Vada isn't on the menu, so find returned undefined, and undefined has no properties.

In TypeScript, find doesn't return a Dish. It returns Dish | undefined, because it might find nothing:

type Dish = { name: string; price: number };
const menu: Dish[] = [ /* dosa, idli */ ];
const dish = menu.find((d) => d.name === "Vada");
// dish: Dish | undefined
console.log(dish.price);
main.ts(5,13): error TS18048: 'dish' is possibly 'undefined'.

The fix: handle the missing case, with an if (narrowing) or optional chaining ?., which gives undefined instead of crashing:

const dish = menu.find((d) => d.name === "Vada");
if (dish) {
  console.log(dish.price);     // here: Dish
} else {
  console.log("Vada is not on the menu");
}
console.log(dish?.price);       // or: undefined, no crash

With the menu holding masala dosa:

Vada is not on the menu
undefined

TypeScript makes you think about the missing case before a customer finds it. This check exists because of strictNullChecks, which "strict": true turns on.

Generics: one function, any type, still checked

firstItem returns the first item of any list. But its return type depends on the list. So it takes a type parameter T, written in angle brackets:

function firstItem<T>(list: T[]): T | undefined {
  return list[0];
}
const firstDish = firstItem(["Dosa", "Idli"]);   // string | undefined
const n: string = firstItem([1, 2, 3]);
main.ts(5,7): error TS2322: Type 'number | undefined' is not assignable to type 'string'.
  Type 'undefined' is not assignable to type 'string'.
  • "A list of T gives back a T, or undefined." T is filled in at each call: a list of strings makes T = string, a list of numbers makes T = number.
  • That's a generic: one function that works for any type and keeps the checks.
  • You've used generics already: Array<string> is the same as string[].

any and unknown: data from outside

Types vanish at runtime, so data that arrives from outside your program (JSON from an API, a file, a form) is never checked by tsc. It can't know what a server will send.

any switches checking off completely:

const order: any = JSON.parse(text);
order.prcie.toFixed(2);   // tsc: no error!

tsc reports nothing, and Node crashes:

TypeError: Cannot read properties of undefined (reading 'toFixed')

any is an escape hatch. Use it as little as possible.

unknown is the safe choice: you may hold it, but you can't use it until you've checked what it is.

const text = '{"dish": "Dosa", "price": 120}';
const order: unknown = JSON.parse(text);
order.price;
main.ts(3,1): error TS18046: 'order' is of type 'unknown'.

Check first, then use:

const text = '{"dish": "Dosa", "price": 120}';
const order: unknown = JSON.parse(text);
if (typeof order === "object" && order !== null && "price" in order) {
  console.log(order.price);
}
120

In strict mode the error in a catch block is also unknown, for the same reason (anything can be thrown):

try {
  JSON.parse("{oops");
} catch (err) {
  console.log(err.message);
}
main.ts(4,15): error TS18046: 'err' is of type 'unknown'.

Fix: if (err instanceof Error) console.log(err.message);.

any unknown
Can hold anything yes yes
Can use .price, call it, etc. yes, unchecked no, not until you narrow it
Bugs slip through to runtime caught by tsc
Use for (almost) never; quick migration from JS outside data: JSON, catch (err)

Setting it up in a real project

npm install --save-dev typescript
npx tsc --init          # creates tsconfig.json ("strict": true)
npx tsc --noEmit        # check every file, write nothing
npx tsc                 # check, then write plain .js files
node main.ts            # Node 24: runs it, types stripped, NOT checked
  • --save-dev installs it as a dev dependency: needed while developing, not when the app runs.
  • npx runs a tool installed in the project.
  • tsconfig.json is TypeScript's settings file. npx tsc --init writes one with "strict": true, "target": "esnext" and "module": "nodenext".
  • Keep strict on. It turns on the checks this episode relies on: undefined checks (strictNullChecks), and no silent any on parameters (noImplicitAny).
  • Put the check in package.json next to the tests from episode 30, so nothing broken gets committed:
{
  "scripts": {
    "test": "tsc --noEmit && node --test"
  }
}

What noImplicitAny catches, on JavaScript copied into a .ts file:

function average(list) {
  return list.reduce((a, b) => a + b, 0) / list.length;
}
console.log(average([4, 5, 3]));
main.ts(1,18): error TS7006: Parameter 'list' implicitly has an 'any' type.
main.ts(2,23): error TS7006: Parameter 'a' implicitly has an 'any' type.
main.ts(2,26): error TS7006: Parameter 'b' implicitly has an 'any' type.

(node main.ts still prints 4: Node never checks.) Adding list: number[] fixes all three, because a and b are then inferred.

Common mistakes (and what really happens)

You wrote What happens Why Fix
function f(items: Item[]) in main.js SyntaxError: Unexpected token ':' types are not JavaScript a .ts file, checked by tsc
withTip(280, "20") JS: 28020. tsc: TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. form input is a string Number(tip)
{ prcie: 30 } JS: NaN. tsc: TS2561: ... 'prcie' does not exist in type 'Item'. Did you mean to write 'price'? typo price
tableNo = "five" TS2322: Type 'string' is not assignable to type 'number'. inferred number keep one type per variable
type: "Veg" TS2820: Type '"Veg"' is not assignable to type 'FoodType'. Did you mean '"veg"'? literal types are exact "veg"
leaving out a required property TS2741: Property 'type' is missing in type ... but required in type 'Dish'. not optional add it, or mark it type?:
price.toFixed(2) on a number-or-string union TS2339: Property 'toFixed' does not exist on type 'string'. (JS: TypeError: price.toFixed is not a function) might be a string narrow with typeof
menu.find(...).price TS18048: 'dish' is possibly 'undefined'. (JS: Cannot read properties of undefined (reading 'price')) find can find nothing if (dish) or dish?.price
asha.phone = "..." on a readonly TS2540: Cannot assign to 'phone' because it is a read-only property. readonly make a new object
const x: any = JSON.parse(text) no tsc error, crash at runtime any turns checks off unknown + checks
err.message in catch TS18046: 'err' is of type 'unknown'. anything can be thrown if (err instanceof Error)
function average(list) in strict mode TS7006: Parameter 'list' implicitly has an 'any' type. no type, can't infer list: number[]
node main.ts to "check" the code runs, prints 28020 Node strips types, never checks npx tsc --noEmit

Mini project: a typed restaurant order system

Everything from this episode in one small program: literal unions for food type and order status, interfaces, an optional note, find returning MenuItem | undefined, pure functions with spread, and a switch over a union.

type FoodType = "veg" | "nonveg";
type Status = "placed" | "cooking" | "served" | "paid";

interface MenuItem {
  name: string;
  price: number;
  type: FoodType;
}
interface OrderLine {
  item: MenuItem;
  qty: number;
}
interface Order {
  table: number;
  lines: OrderLine[];
  status: Status;
  note?: string;
}

const menu: MenuItem[] = [
  { name: "Masala dosa", price: 120, type: "veg" },
  { name: "Chicken biryani", price: 260, type: "nonveg" },
  { name: "Filter coffee", price: 40, type: "veg" },
];

function findItem(name: string): MenuItem | undefined {
  return menu.find((m) => m.name === name);
}

function addLine(order: Order, name: string, qty: number): Order {
  const item = findItem(name);
  if (!item) throw new Error(`${name} is not on the menu`);
  return { ...order, lines: [...order.lines, { item, qty }] };
}

function orderTotal(order: Order): number {
  const sum = order.lines.reduce((t, line) => t + line.item.price * line.qty, 0);
  return Math.round(sum * 1.05);
}

function nextStatus(status: Status): Status {
  switch (status) {
    case "placed": return "cooking";
    case "cooking": return "served";
    case "served": return "paid";
    case "paid": return "paid";
  }
}

let order: Order = { table: 4, lines: [], status: "placed" };
order = addLine(order, "Masala dosa", 2);
order = addLine(order, "Filter coffee", 2);
order = { ...order, status: nextStatus(order.status) };
console.log(`Table ${order.table}: ${order.lines.length} lines, Rs ${orderTotal(order)}, ${order.status}`);
console.log(order.note ?? "no note");
try {
  order = addLine(order, "Pizza", 1);
} catch (err) {
  if (err instanceof Error) console.log(err.message);
}

npx tsc --noEmit main.ts prints nothing (no errors). node main.ts:

Table 4: 2 lines, Rs 336, cooking
no note
Pizza is not on the menu

Things to notice:

  • if (!item) throw ... narrows MenuItem | undefined to MenuItem, so { item, qty } is allowed.
  • nextStatus needs no default: TypeScript knows the four cases cover every possible Status, so the function always returns.
  • err instanceof Error narrows the unknown error.

What the types catch if someone gets an order wrong:

type Status = "placed" | "cooking" | "served" | "paid";
interface Order { table: number; status: Status; note?: string }
const o: Order = { table: "4", status: "ready" };
main.ts(3,20): error TS2322: Type 'string' is not assignable to type 'number'.
main.ts(3,32): error TS2322: Type '"ready"' is not assignable to type 'Status'.

Extend it: add a removeLine(order, name) function, a vegOnly(menu) filter typed as MenuItem[], and a discount?: number on Order that orderTotal applies when present.

Practice

  1. Convert the quiz game from episode 15 to TypeScript: a Question type with text, options and the index of the right answer, and a score(questions, picks) function.
  2. Write a type Order with dish, qty and an optional note, and a function kitchenSlip(order) that prints 2 x Masala dosa or 1 x Pav bhaji (less spicy).
  3. Write formatId(id: number | string): numbers become ORD-0042 (padded to 4 digits), strings are upper-cased.
  4. Turn on strict mode for this JavaScript function and fix every error: function average(list) { return list.reduce((a, b) => a + b, 0) / list.length; }. Also make it return 0 for an empty list.
  5. Write a generic lastItem<T>(list: T[]) that returns the last item, or undefined for an empty list.
Solutions

All five solutions pass npx tsc --strict --noEmit with no errors. The outputs are from node main.ts.

  1. The quiz game:
type Question = {
  text: string;
  options: string[];
  answer: number; // index of the right option
};

const questions: Question[] = [
  { text: "Capital of India?", options: ["Mumbai", "New Delhi", "Kolkata"], answer: 1 },
  { text: "2 + 2 * 2?", options: ["8", "6", "4"], answer: 1 },
];

function score(qs: Question[], picks: number[]): number {
  return qs.reduce((total, q, i) => total + (picks[i] === q.answer ? 1 : 0), 0);
}
console.log(`Score: ${score(questions, [1, 0])} / ${questions.length}`);
Score: 1 / 2
  1. An optional note:
type Order = { dish: string; qty: number; note?: string };

function kitchenSlip(o: Order): string {
  return `${o.qty} x ${o.dish}${o.note ? ` (${o.note})` : ""}`;
}
console.log(kitchenSlip({ dish: "Masala dosa", qty: 2 }));
console.log(kitchenSlip({ dish: "Pav bhaji", qty: 1, note: "less spicy" }));
2 x Masala dosa
1 x Pav bhaji (less spicy)
  1. Narrowing a union:
function formatId(id: number | string): string {
  if (typeof id === "number") return "ORD-" + String(id).padStart(4, "0");
  return id.toUpperCase();
}
console.log(formatId(42));
console.log(formatId("ord-0099"));
ORD-0042
ORD-0099

After the if returns for numbers, TypeScript knows id is a string on the last line, so toUpperCase is allowed.

  1. Strict mode first reports three TS7006: Parameter ... implicitly has an 'any' type. errors (for list, a and b). The fix:
function average(list: number[]): number {
  if (list.length === 0) return 0;
  return list.reduce((a, b) => a + b, 0) / list.length;
}
console.log(average([4, 5, 3]));
console.log(average([]));
4
0
  1. A generic:
function lastItem<T>(list: T[]): T | undefined {
  return list[list.length - 1];
}
const lastDish = lastItem(["Dosa", "Idli", "Vada"]);
const lastPrice = lastItem([120, 60]);
console.log(lastDish?.toUpperCase(), lastPrice);
console.log(lastItem([]));
VADA 60
undefined

lastDish is string | undefined, so ?. is needed before toUpperCase.

Quick quiz

What does tsc say?

type Order = { dish: string; qty: number };

const o: Order = { dish: "Dosa", qty: "2" };
  • A. Nothing, it's fine
  • B. Type 'string' is not assignable to type 'number'.
  • C. SyntaxError: Unexpected token ':'
  • D. It prints 2
Answer

B. qty must be a number, but "2" in quotes is a string. Real output:

main.ts(3,34): error TS2322: Type 'string' is not assignable to type 'number'.

C would only happen if you put this code in a .js file and ran it with Node. D is wrong because tsc --noEmit never runs the code. Fix: qty: 2.

Interview questions

  • What is TypeScript? A superset of JavaScript that adds static types. tsc checks the types and compiles to plain JavaScript; any valid JavaScript is valid TypeScript.
  • Static vs dynamic typing? Static: types are checked from the code before it runs (TypeScript, Java). Dynamic: types are only known while running (JavaScript, Python).
  • Does TypeScript make code run faster, or check types at runtime? No. Types are erased; the output is ordinary JavaScript. Data from outside (APIs, files, forms) must still be validated at runtime.
  • What does node main.ts do in Node 24? It strips the type annotations and runs the code. It does not type-check; use tsc --noEmit for that.
  • What is type inference? TypeScript working out a type from the value: let n = 5 is a number without an annotation.
  • type vs interface? Both describe object shapes. type can also name unions and other types; interface can be extended and re-opened (declaration merging). For plain objects they are interchangeable.
  • What is a union type? A literal type? A | B means a value of type A or B. A literal type is one exact value, like "veg"; unions of literals act like a fixed list of choices.
  • What is narrowing? Using checks (typeof, in, instanceof, equality, truthiness) so TypeScript knows a more specific type inside a branch.
  • Why does array.find() return T | undefined? It returns undefined when nothing matches; with strictNullChecks you must handle that case.
  • What are generics? Type parameters (<T>) that let one function or type work with many types while keeping the link between input and output types.
  • any vs unknown? Both accept any value. any disables checking; unknown forces you to narrow before use, so it's the safe choice for outside data and caught errors.
  • What does "strict": true enable? A group of checks, including strictNullChecks (null/undefined handling) and noImplicitAny (no silent any parameters).
  • What does tsc --noEmit do? Type-checks the project without writing any output files; common in CI and npm test.
  • What is readonly? A property that can be set when the object is created but not reassigned later (a compile-time check only).

Glossary

Term Meaning Example
Type what kind of value is allowed number, string
Dynamic typing types are only known while the program runs JavaScript
Static typing types are checked from the code before it runs TypeScript
Type checking comparing every value and use against its type tsc
Coercion JavaScript quietly converting a value to another type 280 + "20" → "28020"
NaN "Not a Number": the result of failed maths undefined * 2
TypeScript JavaScript plus type notes, in .ts files main.ts
.ts file a TypeScript source file main.ts
tsc the TypeScript compiler: checks types and writes .js npx tsc
Compile turn source code into another form (here .ts → .js) npx tsc main.ts
--noEmit check only, don't write any files npx tsc --noEmit
Type erasure types are removed from the output; they don't exist at runtime the main.js tsc writes
Type stripping Node removing type notes so it can run a .ts file, without checking node main.ts
Type annotation a type written after a colon tip: number
Return type the type a function gives back, after its brackets ): number
void the function returns nothing greet(name: string): void
Type inference TypeScript working out a type by itself let n = 5 is number
Type alias a name for a type, made with type type Item = { ... }
interface a named description of an object's shape interface Customer { ... }
Optional property a property that may be left out, written with ? spicy?: boolean
readonly a property that can't be changed after creation readonly phone: string
Literal type a type that is one exact value "veg"
Union type "this or that", written with a vertical bar between the types number bar string (see above)
Narrowing a check that makes a type more specific inside a block if (typeof price === "string")
typeof gives a value's type as a string at runtime typeof 40 is "number"
in checks whether an object has a property "price" in order
instanceof checks whether a value was made by a class err instanceof Error
Optional chaining ?. reads a property only if the value isn't null/undefined dish?.price
Nullish coalescing ?? a fallback when the value is null/undefined email ?? "no email"
Generic a function or type with a type parameter firstItem<T>(list: T[])
Type parameter a placeholder for a type, filled in at each use T
any "anything, don't check": turns type checking off const x: any
unknown "anything, check before use": the safe version const x: unknown
tsconfig.json TypeScript's settings file for a project "strict": true
Strict mode the group of strongest checks strictNullChecks, noImplicitAny
strictNullChecks undefined and null must be handled 'dish' is possibly 'undefined'
noImplicitAny parameters can't silently become any TS7006
Dev dependency a package needed only while developing npm install --save-dev typescript
npx runs a tool installed in the project npx tsc
Error code (TS2345) the number of a TypeScript error, useful for searching TS18048

Summary

  • JavaScript is dynamically typed: 280 + "20" quietly becomes "28020", a typo gives NaN, and no error is shown.
  • TypeScript is JavaScript plus types in .ts files. tsc checks every line before running (npx tsc --noEmit), and writes plain .js with the types erased.
  • Types in a .js file are a SyntaxError. node main.ts strips types but never checks them.
  • Inference fills in most types; write types on function parameters. Basics: string, number, boolean, number[].
  • Describe objects with type or interface; ? makes a property optional, readonly stops changes.
  • Literal unions ("veg" | "nonveg") give fixed choices; union types (number | string) must be narrowed (typeof) before use.
  • find() returns T | undefined: handle it with if or ?. (TS18048: 'dish' is possibly 'undefined').
  • Generics (<T>) keep checks for any type. Prefer unknown over any for outside data. Keep "strict": true, and put tsc --noEmit in npm test.

Next episode: Intermediate project: a CLI to-do app. Modules, files, JSON, errors and tests, all together in one real command-line app.