# Learn TypeScript: A Free Step-by-Step Tutorial for Beginners

> Learn TypeScript free, in your browser, with nothing to install: six lessons in order (types and inference, object shapes, unions and narrowing, functions, generics, data from outside), a worked example that turns a broken JavaScript file into TypeScript, and a two-week plan. Whether you need JavaScript first and how long it takes.

TypeScript is JavaScript with types: you write down what shape each value has, and a checker tells you where the code contradicts itself before it ever runs. Most of it is six ideas. This free tutorial teaches them in order, in a browser, with nothing to install and no account.

## The short answer

1. **Know a little JavaScript first**: variables, functions, arrays and objects. TypeScript adds to JavaScript; it does not replace it. Two weeks of JavaScript is enough to start.
2. **Open the TypeScript Playground** (typescriptlang.org/play). It is free, made by the TypeScript team, needs no install and works in a phone browser. Type on the left, read the errors as you go.
3. **Learn the six lessons in order**: (1) type annotations and inference; (2) object shapes with `interface` and `type`; (3) unions and narrowing; (4) function types; (5) generics; (6) data from outside your program, and the `strict` setting.
4. **Predict the error before you read it.** For every example below, say which line the checker will refuse and why, then look. The prediction is where the learning happens.
5. **Convert one small JavaScript file of your own** to TypeScript, the way the worked example below does. Fix what the checker finds without ever writing `any`.
6. **Install it for a real project** when the lessons are done: `npm install --save-dev typescript`, `npx tsc --init`, keep `"strict": true`.

## What TypeScript is, and what it is not

TypeScript is a language built on JavaScript by Microsoft, free and open source. Every JavaScript program is already a TypeScript program; TypeScript adds a way to say what each value is (a number, a list of strings, a book with a title and a price) and a checker that reads those statements and reports every place the code breaks them.

The idea most tutorials leave until late, and the one that prevents the most confusion: **the types are erased before the program runs.** The checker works while you write. Then the types are removed and plain JavaScript is what runs in the browser or in Node.js. So TypeScript cannot make a program slower, and it cannot check anything that only exists while the program runs, such as what a server really sent back.

| TypeScript catches, while you type | TypeScript cannot catch |
| --- | --- |
| A misspelt property name (`titel` for `title`) | A server that sends a different shape from the one you declared |
| A text value where a number is needed | A wrong calculation that uses the right types (price times 2 where you meant plus 2) |
| A value that may be missing, used as if it were always there | What a user types into a form |
| A function called with too few arguments, or the wrong ones | A slow or badly designed program |
| A case you forgot to handle after adding a new option | Anything hidden behind `any`, which switches the checker off |

Why learn it now: in GitHub's 2025 Octoverse report, TypeScript became the most used language on GitHub in August 2025, ahead of Python and JavaScript, for the first time. Most new web projects, front end and back end, start in it.

## Set up in two minutes (free, nothing to install)

Open the TypeScript Playground in any browser. Code goes on the left; the JavaScript it becomes shows on the right; errors are underlined in red, and the Errors tab lists them. It checks with `strict` on, which is what you want from the first day. Everything in lessons 1 to 6 runs there.

When you want TypeScript on your own computer, you need Node.js, then four commands in an empty folder:

```
npm init -y
npm install --save-dev typescript
npx tsc --init          # writes tsconfig.json, with "strict": true
npx tsc --noEmit        # check every file, write nothing
```

- `npx tsc` checks the files and writes the JavaScript. `npx tsc --watch` keeps checking as you save.
- Current Node.js runs a `.ts` file directly (`node app.ts`) by removing the types, as long as the file uses only syntax that can be erased. It does not check the types: `tsc --noEmit` still does that.
- A code editor with TypeScript support (Visual Studio Code has it built in) shows the same errors as you type, and hovering over any name shows its type. Hovering is how you read TypeScript.

## Lesson 1: types and inference

You state a type after a colon. Often you do not need to: TypeScript works the type out from the value, which is called inference. The three you meet first are `string`, `number` and `boolean`; a list is written `string[]`.

```
let price: number = 20;
let title = "Clean Code";        // no annotation: inferred as string

title = 42;
// Error: Type 'number' is not assignable to type 'string'.

const tags: string[] = ["code", "craft"];
tags.push(7);
// Error: Argument of type 'number' is not assignable to parameter of type 'string'.
```

- **Annotate the edges, let inference do the middle.** Write types on function parameters and on data that comes from outside; leave local variables to inference.
- **`any` switches the checker off** for that value and for everything it touches. Treat it as a bug you have chosen to keep.
- **`unknown` is the safe version**: a value you know nothing about yet, which the checker will not let you use until you have tested what it is (lesson 6).

**Try:** declare `let stock = 12`, then assign `"twelve"` to it. Predict the exact error. Then hover over `stock` and read its type.

## Lesson 2: object shapes with interface and type

Most real data is objects. An `interface` names the shape once so every function can share it. A question mark makes a property optional; `readonly` forbids changing it after creation.

```
interface Book {
  id: number;
  title: string;
  author?: string;          // may be absent
  readonly isbn: string;    // cannot be reassigned
}

const book: Book = { id: 1, title: "Learning SQL", isbn: "isbn-001" };

book.isbn = "isbn-002";
// Error: Cannot assign to 'isbn' because it is a read-only property.

book.author.toUpperCase();
// Error: 'book.author' is possibly 'undefined'.

const typo: Book = { id: 2, titel: "Oops", isbn: "isbn-003" };
// Error: Object literal may only specify known properties, but 'titel'
// does not exist in type 'Book'. Did you mean to write 'title'?
```

The second error is the one that pays for learning TypeScript. In JavaScript that line crashes when a user opens a book with no author, perhaps months later. Here it cannot be written. The fix is to say what happens when the author is missing:

```
const author = book.author?.toUpperCase() ?? "Unknown author";
```

- `?.` stops and gives `undefined` if the value before it is missing. `??` supplies a value to use in that case.
- A `type` alias can name any type, including the unions of lesson 3: `type Id = number | string`. For object shapes, `interface` and `type` do nearly the same job; pick one habit and keep it.
- TypeScript compares shapes, not names. Any object with the right properties is a `Book`, wherever it came from.

**Try:** write an interface for a customer with a name, a country and an optional phone number. Create one without a phone, then try to read the length of the phone number.

## Lesson 3: unions and narrowing, the lesson that makes TypeScript useful

A union says a value is one of several types: `number | string`. You may only do what is safe for all of them, until you check which one you have. After the check, TypeScript knows too. That is narrowing.

```
type Id = number | string;

function label(id: Id): string {
  if (typeof id === "number") {
    return "#" + id.toFixed(0);   // here, id is a number
  }
  return id.toUpperCase();        // here, id can only be a string
}
```

The pattern you will use every week is a union of object shapes that share one field naming the case. Each case carries only the data that exists in that case:

```
type Order =
  | { status: "pending" }
  | { status: "paid"; paidAt: Date }
  | { status: "cancelled"; reason: string };

function describe(order: Order): string {
  switch (order.status) {
    case "pending":
      return "Waiting for payment";
    case "paid":
      return "Paid on " + order.paidAt.toDateString();
    case "cancelled":
      return "Cancelled: " + order.reason;
  }
}
```

Two things happened that plain JavaScript cannot do. Inside `case "paid"`, `order.paidAt` exists, and inside `case "pending"` it does not: a pending order with a payment date cannot be built at all. And the function is checked for completeness. Add a fourth case to the type, `{ status: "refunded"; amount: number }`, and change nothing else. The checker points at `describe`:

```
// Error: Function lacks ending return statement and return type
// does not include 'undefined'.
```

It has found the place you forgot to update. In a large program it finds all of them. This is what people mean when they say TypeScript makes changes safe.

**Try:** model a traffic light as a union of three shapes, where only the red one carries `secondsLeft`. Write a function that returns what a driver should do, then add a fourth state and watch the function fail to compile.

## Lesson 4: functions

A function states the type of each parameter and of what it returns. Read that first line before the body: it is documentation that cannot go out of date.

```
function total(prices: number[], discount = 0): number {
  const sum = prices.reduce((a, b) => a + b, 0);
  return sum * (1 - discount);
}

total([20, 35]);          // 55
total([20, 35], 0.1);     // 49.5
total("20, 35");
// Error: Argument of type 'string' is not assignable to parameter of type 'number[]'.

type Formatter = (amount: number) => string;
const euros: Formatter = (amount) => "EUR " + amount.toFixed(2);

function log(message: string, note?: string): void {
  console.log(note ? message + " (" + note + ")" : message);
}
```

- A default value (`discount = 0`) makes the parameter optional and gives it a type by inference.
- `note?: string` is optional with no default: inside the function it is `string | undefined`, so you must check it.
- `void` means the function returns nothing you should use.
- A function type (`Formatter`) describes a callback. In `euros`, `amount` needs no annotation: TypeScript takes it from `Formatter`.
- Always write the return type on functions other code depends on. Then a mistake inside the body is reported inside the body, not far away where the result is used.

## Lesson 5: generics

A generic is a type with a blank in it. `T` below means "whatever type the caller brings", and the function promises to give the same type back. Without generics you would write `first` once for numbers and again for strings, or give up and use `any`.

```
function first<T>(items: T[]): T | undefined {
  return items[0];
}

const n = first([3, 1, 2]);       // number | undefined
const s = first(["a", "b"]);      // string | undefined

interface ApiResult<T> {
  data: T;
  fetchedAt: Date;
}

function byId<T extends { id: number }>(items: T[], id: number): T | undefined {
  return items.find((item) => item.id === id);
}
```

`T extends { id: number }` is a constraint: any type will do, provided it has a numeric `id`. `byId(["a"], 1)` is refused, because a string has no `id`.

You will read generics far more often than you write them, because every library uses them. Four built-in ones cover most everyday needs:

| Written | Means | Used for |
| --- | --- | --- |
| `Partial<Book>` | A `Book` with every property optional | A form that is half filled in; an update that changes some fields |
| `Pick<Book, "id" | "title">` | Only those two properties | A short list view |
| `Record<string, number>` | An object whose keys are strings and whose values are numbers | Stock counts by ISBN |
| `Promise<Book>` | A `Book` that arrives later | Anything loaded from a server |

## Lesson 6: data from outside, and the strict setting

Remember that types are erased. When data arrives from a server, a file or a form, writing `const book: Book = await res.json()` is a promise nobody checks: if the server sends something else, the program fails later, somewhere unrelated. The honest type for outside data is `unknown`, and the checker will not let you touch it until you have tested it.

```
function isBook(value: unknown): value is Book {
  return (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    typeof value.id === "number" &&
    "title" in value &&
    typeof value.title === "string" &&
    "isbn" in value &&
    typeof value.isbn === "string"
  );
}

async function loadBook(id: number): Promise<Book> {
  const res = await fetch("/api/books/" + id);
  const data: unknown = await res.json();
  if (!isBook(data)) {
    throw new Error("Unexpected response for book " + id);
  }
  return data;      // here, data is a Book
}
```

`value is Book` makes `isBook` a type guard: a real check that runs in the program, which TypeScript then trusts. In larger projects a validation library writes these checks for you; the idea is the same. Check at the door, and everything inside can rely on the types.

Last, the setting that decides how much TypeScript helps you. In `tsconfig.json`:

```
{
  "compilerOptions": {
    "strict": true
  }
}
```

`strict` turns on the checks this tutorial has relied on, above all the one that tracks values that may be `undefined` or `null`. Learning with it off teaches a weaker language and leaves habits to unlearn. Start strict and stay strict.

## A worked example: one broken JavaScript file, converted

This small JavaScript file works out a shopping cart total. It has three bugs. Read it and find what you can before going on.

```
// cart.js
function cartTotal(items, coupon) {
  let total = 0;
  for (const item of items) {
    total += item.price * item.quantity;
  }
  if (coupon.percent) {
    total = total - (total * coupon.percent) / 100;
  }
  return total.toFixed(2);
}

const total = cartTotal([{ price: "20", qty: 2 }, { price: 35, quantity: 1 }]);
console.log("Total: " + (total + 5));   // add 5 for delivery
```

JavaScript runs it without a word of warning and crashes on the `coupon.percent` line, because no coupon was passed. Fix that and it prints a wrong total with no error at all. Now convert it. Paste it into the Playground and add only the types you believe are true:

```
interface CartItem {
  price: number;
  quantity: number;
}

interface Coupon {
  percent: number;
}

function cartTotal(items: CartItem[], coupon: Coupon) {
```

| Step | What the checker says | The bug it found | The fix |
| --- | --- | --- | --- |
| 1 | `Expected 2 arguments, but got 1.` | The call passes no coupon, so `coupon.percent` crashes | Decide the truth: a coupon is optional. Write `coupon?: Coupon` |
| 2 | `'coupon' is possibly 'undefined'.` | The same bug, now shown at the line that would crash | Test for the coupon itself: `if (coupon)` |
| 3 | `Type 'string' is not assignable to type 'number'.` on `price: "20"`, and `qty` is not a known property | A price stored as text, and a misspelt field that turned the whole total into `NaN` (not a number) | Write `price: 20` and `quantity: 2` |
| 4 | Add the return type `: number`, and: `Type 'string' is not assignable to type 'number'.` | `toFixed` returns text, so `total + 5` glued a 5 onto the end instead of adding it | Return the number; format it only where it is printed |

```
function cartTotal(items: CartItem[], coupon?: Coupon): number {
  let total = 0;
  for (const item of items) {
    total += item.price * item.quantity;
  }
  if (coupon) {
    total -= (total * coupon.percent) / 100;
  }
  return total;
}

const total = cartTotal([
  { price: 20, quantity: 2 },
  { price: 35, quantity: 1 },
]);
console.log("Total: " + (total + 5).toFixed(2));   // Total: 80.00
```

Notice what the work was. You did not learn new syntax in those four steps; you answered four questions about your own program (is a coupon required, is a price a number, what does this function return) and the checker held the code to your answers. That is the skill. Do the same with a small file of your own and you have finished the beginner stage.

## Which route fits where you are starting from

| You are starting from | Do this first | Then |
| --- | --- | --- |
| Never coded | Two weeks of JavaScript: variables, functions, arrays, objects, loops | This tutorial from lesson 1. Learning both at once is possible, but you will not know which language an error belongs to |
| You know JavaScript | Lessons 1 and 2 in one sitting; they will feel familiar | Spend most of your time on lessons 3 and 6, then convert a file of your own |
| You know Java, C#, Kotlin or Swift | Lesson 2's last point: types match by shape, not by name | Lesson 3. Unions and narrowing replace much of what you would do with classes |
| You build with React, Vue or Node already | The worked example, on one real component or route of yours | Lesson 5, so you can read your framework's types |
| You only have a phone | The Playground in the phone's browser | Short lessons you can finish in one sitting; typing long programs on a phone is slow, reading and predicting is not |

What we see from LoWisa learners: two learners, in three posts, described their first day in nearly the same words, that they "didn't know where to start", and both wrote that it began to click once they finished lessons instead of stopping halfway. The order above is there so you never have to choose what comes next.

## A two-week plan, thirty minutes a day

| Days | Do | You can now |
| --- | --- | --- |
| 1 | Open the Playground. Lesson 1. Break ten lines on purpose and read each error | Read a type error without panic |
| 2 to 3 | Lesson 2. Write interfaces for three things you know (a song, a match, a recipe) | Describe any object |
| 4 to 6 | Lesson 3. One union of your own with three cases and a `switch`; add a fourth case | Model "one of several" and let the checker find what you forgot |
| 7 | Rest. Write one example from memory | Keep what you have |
| 8 | Lesson 4. Add parameter and return types to five small functions | Read any function signature |
| 9 to 10 | Lesson 5. Write `first`, `last` and `byId` yourself; hover over an array method and read its generic type | Read library types |
| 11 | Lesson 6. Write one type guard for data of your own | Handle outside data honestly |
| 12 to 14 | Install TypeScript. Convert one small JavaScript file of yours, strict on, no `any` | Use TypeScript for real |

After the two weeks, write one typed function a day from memory for another two (the spaced reviews in [How to memorize faster](/guides/how-to-memorize-faster/) work for code exactly as for facts). Then learn what this tutorial leaves out, in this order: your framework's own types, `keyof` and mapped types, and the rest of `tsconfig.json`.

## The mistakes that keep beginners stuck

- **Reaching for `any` to make an error go away.** The error was the lesson. Use `unknown` and a check, or fix the type.
- **Silencing the checker with `as`.** `data as Book` is you telling TypeScript to stop looking. It is right far less often than it feels.
- **Learning with `strict` off.** You skip the missing-value checks, which are the main thing TypeScript gives you.
- **Annotating everything.** `const count: number = 0` adds noise. Annotate parameters, return types and outside data; let inference do the rest.
- **Starting with advanced types.** Conditional and mapped types are for library authors first. Unions, narrowing and generics are what every job needs.
- **Watching a four-hour video without typing.** TypeScript looks obvious on a screen and falls apart at an empty file. Type every example and predict each error.
- **Reading only the first line of a long error.** The last lines name the exact mismatch; the first only says where it surfaced.
- **Believing a type about data you never checked.** Types are erased. Check outside data at the door (lesson 6).

## Your TypeScript learning plan

1. Know basic JavaScript first: variables, functions, arrays, objects.
2. Open the TypeScript Playground (typescriptlang.org/play). Free, nothing to install.
3. Lesson 1: annotations and inference. Lesson 2: interface, optional (?), readonly.
4. Lesson 3: unions and narrowing; one shared field naming each case; a switch the checker completes.
5. Lesson 4: parameter and return types. Lesson 5: generics, Partial, Pick, Record, Promise.
6. Lesson 6: outside data is unknown until a type guard has checked it. Keep "strict": true.
7. Predict every error before you read it. Never write any to silence one.
8. Convert one small JavaScript file of your own. One typed function a day from memory for two weeks.

## Frequently asked questions

### Can I learn TypeScript without knowing JavaScript?

You can start, but you will learn JavaScript on the way, because TypeScript is JavaScript with types added: the variables, functions, arrays and objects are JavaScript. If you have never coded, spend about two weeks on basic JavaScript first, then start TypeScript. Learning both at once is possible, but every error then raises a second question: which language is it about?

### How long does it take to learn TypeScript?

If you already know JavaScript, the core (types, object shapes, unions and narrowing, functions, generics) takes about two weeks at thirty minutes a day, typing every example. You can read most TypeScript code after the first week. Being fluent with a framework's types and with advanced types takes a few months of using it on real projects. Starting from no coding at all, add the time to learn basic JavaScript first.

### Is TypeScript free to learn and use?

Yes. TypeScript is free and open source, and so are the official Handbook and the Playground on typescriptlang.org, where you can write and check TypeScript in a browser with nothing to install. This tutorial is free too. Paid courses teach the same language; what makes it stick is typing the examples and converting code of your own.

### Is TypeScript hard to learn?

The basics are easy if you know JavaScript: a type annotation is a colon and a word. Three parts are harder at first: values that may be missing (`undefined`), unions that must be narrowed before use, and reading generic types in libraries. Lessons 2, 3 and 5 above teach exactly those three, on examples small enough to hold in your head.

### Should I learn JavaScript or TypeScript first?

JavaScript first, but briefly. You need variables, functions, arrays and objects before types have anything to describe. You do not need to master JavaScript: once you can write a small program, move to TypeScript, and you will keep learning JavaScript inside it with a checker that catches your mistakes.

### Is TypeScript worth learning in 2026?

For web work, yes. GitHub's 2025 Octoverse report found that TypeScript became the most used language on GitHub in August 2025, ahead of Python and JavaScript, and most new front-end and Node.js projects start in it. If you write JavaScript for work, you will read TypeScript whether or not you choose it.

## Sources

- [The TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/intro.html). The TypeScript team, Microsoft. typescriptlang.org (the official documentation; read 24 November 2026).
- [TypeScript Playground](https://www.typescriptlang.org/play/). The TypeScript team, Microsoft. typescriptlang.org (free, in the browser).
- [Modules: TypeScript (running TypeScript files by removing the types)](https://nodejs.org/api/typescript.html). Node.js. Node.js API documentation (read 24 November 2026).
- [Octoverse: A new developer joins GitHub every second as AI leads TypeScript to #1](https://github.blog/news-insights/octoverse/octoverse-a-new-developer-joins-github-every-second-as-ai-leads-typescript-to-1/). GitHub Staff (2025). The GitHub Blog, 28 October 2025.

## Learn TypeScript lesson by lesson

In the LoWisa app, TypeScript is one of 37 programming language courses: short lessons from why TypeScript exists through object types, unions and narrowing, functions, generics, the compiler settings and typed data from an API, each level ending with a checkpoint and flashcards. Level 0 is free; the levels after it are on a plan. It is a phone app, with no web version. The app is on Google Play and the App Store.

---

Source: https://lowisa.dev/guides/learn-typescript/ · Updated 2026-11-24 · By Samuel Jesse, founder of LoWisa
