Your first TypeScript program

Topic 3 of 3 in Getting started7 min readIntermediateFree course

Overview

In this lesson you’ll write a small but complete program, run it, and then do what you’ll do every day as a TypeScript developer: read type errors and fix them. Error messages are TypeScript’s main way of talking to you, so learning to read them quickly pays off for the whole course.

A complete program

Create src/cart.ts:

TypeScript
type Item = {
  name: string;
  price: number;
  quantity: number;
};

const cart: Item[] = [
  { name: "Notebook", price: 3.5, quantity: 4 },
  { name: "Pen", price: 1.25, quantity: 10 },
];

function lineTotal(item: Item): number {
  return item.price * item.quantity;
}

let total = 0;
for (const item of cart) {
  total += lineTotal(item);
}

console.log(`${cart.length} items, total ${total.toFixed(2)}`);
Terminal
node src/cart.ts
Text
2 items, total 26.50

Three TypeScript features appear here:

  • type Item = { … } describes the shape of an object: a name that is a string, and price and quantity that are numbers. (Object types goes deeper.)
  • cart: Item[] says cart is an array of Items. Every object in it is checked against the shape.
  • (item: Item): number annotates the parameter and the return value.

Notice what we didn’t annotate: total, item in the loop, the result of lineTotal(item). TypeScript infers those from the code. You’ll learn the rules in Type annotations and inference.

Reading an error

Make a typo — item.quantitiy — and run npx tsc:

Text
src/cart.ts(13,28): error TS2551: Property 'quantitiy' does not exist on type 'Item'. Did you mean 'quantity'?

Reading a TypeScript error: src/cart.ts(4,7): error TS2322: Type ‘string’ is not assignable to type ‘number’. The parts are the file (src/cart.ts), the line (4), the column (7), the error code (TS2322) and what went wrong. Read the message from left to right: the value’s type comes first, the expected type last. Search for the code (TS2322) when a message is unclear. Longer errors indent extra detail underneath.

Every error has the same parts: where (file, line, column), an error code, and a message. In the editor you see the same message by hovering over the red squiggle.

The errors you’ll meet first

“Property does not exist” (TS2339, TS2551)

You used a property the type doesn’t have — usually a typo, sometimes a wrong assumption about the data. TS2551 adds a suggestion when a similar name exists.

“Type X is not assignable to type Y” (TS2322)

The most common message in TypeScript. Read it as: “this value is an X, but this place needs a Y”.

TypeScript
function label(total: number): string {
  if (total > 20) return "Free shipping";
  return total;
}
Text
error TS2322: Type 'number' is not assignable to type 'string'.

The function promised to return a string, but one path returns a number.

“Argument of type X is not assignable to parameter of type Y” (TS2345)

The same idea, for function arguments:

TypeScript
label("26.5");
// error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

“Expected 2 arguments, but got 1” (TS2554)

You called a function with too few (or too many) arguments. JavaScript would quietly pass undefined; TypeScript stops you. Hovering over the function shows what it needs.

Long errors

When types are nested, messages get longer — TypeScript explains why, one level per indented line:

Text
error TS2322: Type '{ name: string; price: string; quantity: number; }' is not assignable to type 'Item'.
  Types of property 'price' are incompatible.
    Type 'string' is not assignable to type 'number'.

Read the last line first: that’s the actual mismatch (price is a string). The lines above show where it sits.

Fixing errors properly

When TypeScript complains, it’s almost always right. The fix belongs in the code:

  • correct the typo;
  • convert the value (Number(input));
  • handle the missing case;
  • or, if your intention was different, fix the type to describe what you really meant.

Escape hatches (use sparingly)

TypeScript has ways to silence it:

TypeScript
// @ts-expect-error -- testing that invalid input is rejected
label("26.5");
  • // @ts-expect-error suppresses the error on the next line — and becomes an error itself if there’s nothing to suppress. That makes it perfect for tests and examples that show code TypeScript should reject. This course uses it in many solutions.
  • // @ts-ignore suppresses the next line silently, even when the line is fine. Avoid it.
  • any turns off checking for a value entirely (any, unknown and never).

Each of these trades safety for convenience. Treat them as a note saying “the types are wrong here, on purpose” — always with a comment explaining why.

Run vs check, again

Try the broken program with node src/cart.ts: it runs, and prints NaN for the total — the typo produced undefined, and 3.5 * undefined is NaN. Only npx tsc tells you why. Get into the habit of keeping npx tsc --watch running in a terminal, or of looking at the Problems panel, while you code.

Error-reading routine: find the line, read the last line of the message first, ask “what type is the value, what type does this place need?”, then fix the code — not the warning.

Exercise

Fix the shopping cart

The starter compiles with four errors (run npx tsc to see them): a misspelled property, a missing argument, a string passed where a number is expected, and a function that can return the wrong type. Read each error, fix the code — don’t add any or @ts-ignore — and make the program print exactly the three lines in the comment at the bottom.

TypeScript
type Item = { name: string; price: number; quantity: number };

const cart: Item[] = [
  { name: "Notebook", price: 3.5, quantity: 4 },
  { name: "Pen", price: 1.25, quantity: 10 },
];

function lineTotal(item: Item): number {
  return item.price * item.quantitiy;
}

function cartTotal(items: Item[], discount: number): number {
  let total = 0;
  for (const item of items) total += lineTotal(item);
  return total * (1 - discount);
}

function label(total: number): string {
  if (total > 20) return "Free shipping";
  return total;
}

const total = cartTotal(cart);
console.log(`Items: ${cart.length}`);
console.log(`Total: ${total.toFixed(2)}`);
console.log(label("26.5"));

// Expected output:
// Items: 2
// Total: 23.85
// Free shipping

Summary

  • Errors look like file(line,col): error TSxxxx: message — go to the line, read the message, fix the cause.
  • “Type X is not assignable to type Y”: the value has type X but the place needs Y.
  • Common first errors: misspelled properties (TS2551/2339), wrong arguments (TS2345), missing arguments (TS2554), wrong return values (TS2322).
  • Fix the code rather than silencing the checker; @ts-expect-error is for intentional, documented exceptions.
  • Hover in the editor to see what TypeScript thinks a value’s type is — most confusion ends there.