Tutorials / TypeScript: Beginner to Advanced / Why TypeScript? What it is and what it is not

Why TypeScript? What it is and what it is not

12 min read typescript
Course contents (16 lessons)
  1. Getting started
  2. Why TypeScript? What it is and what it is not
  3. Setting up TypeScript: tsc and tsconfig.json
  4. Core types
  5. Basic types: primitives, arrays, tuples, any and unknown
  6. Typing functions: parameters, returns, optionals and overloads
  7. Objects, interfaces and type aliases
  8. Unions, literals and enums
  9. Union types and type narrowing
  10. Literal types, enums and as const
  11. Classes and generics
  12. Classes in TypeScript
  13. Generics: writing reusable typed code
  14. Built-in utility types: Partial, Pick, Omit, Record and more
  15. Advanced types
  16. Mapped and conditional types
  17. Modules, type imports and declaration files
  18. TypeScript in real projects
  19. Typing async code and API responses
  20. Strict mode and compiler flags that matter
  21. Migrating a JavaScript project to TypeScript
  22. Final project: a type-safe task manager

JavaScript with types

TypeScript is JavaScript plus a type system. You write almost the same code, and add notes about what kind of value each variable, parameter and return value holds. A tool called the compiler reads those notes, checks your code against them, and then removes them. What is left is plain JavaScript that runs in any browser or in Node.js.

TypeScript is made by Microsoft and is open source. It is not a different runtime and it does not make code faster. Its job is to find mistakes before the code runs.

A bug that JavaScript hides

Look at this JavaScript function:

function totalPrice(price, quantity) {
  return price * quantity;
}

console.log(totalPrice("100", 3));  // 300, by luck
console.log(totalPrice("100", "x")); // NaN
console.log(totalPrice(100));        // NaN

All three calls run. JavaScript does not complain. The second and third return NaN, and the bug appears later somewhere else, such as a blank "NaN" in the price shown to a customer. Finding where that came from can take an hour.

The same function in TypeScript:

function totalPrice(price: number, quantity: number): number {
  return price * quantity;
}

console.log(totalPrice(100, 3)); // 300

The : number parts are type annotations. Now if you write totalPrice("100", 3), the editor underlines it in red with the message Argument of type 'string' is not assignable to parameter of type 'number'. You see the problem as you type, with no need to run anything.

What you get in practice

Mistakes caught early. Typos in property names, wrong argument types, missing arguments, and calling a method that does not exist. These are among the most common bugs, and the compiler finds them for you.

Better autocomplete. Because the editor knows the shape of your data, it can suggest property names and show the documentation for each function as you type. Even JavaScript developers get this benefit, since VS Code uses the TypeScript engine for JavaScript files too.

Safe refactoring. Rename a property, and the compiler lists every place that still uses the old name. In a large code base this alone is worth the effort.

Types as documentation. A signature like function sendEmail(to: string, options: { subject: string; html?: string }): Promise<void> tells you how to call it without reading the body. Unlike a comment, it cannot go out of date, because the compiler checks it.

A second small example

interface User {
  id: number;
  name: string;
  email?: string;   // optional
}

function greet(user: User): string {
  return `Hello, ${user.name}`;
}

const sara: User = { id: 1, name: "Sara" };
console.log(greet(sara));

// greet({ id: 2, nme: "Ali" });
// Error: Object literal may only specify known properties,
// and 'nme' does not exist in type 'User'. Did you mean 'name'?

That commented-out call would be a silent bug in JavaScript. Here the compiler even suggests the right spelling.

What TypeScript does not do

I want to be honest about the limits, because beginners often expect too much.

  • It does not check at runtime. Types are removed when the code is compiled. If a server sends you data in a different shape from what you declared, TypeScript will not notice while the program runs. We cover this in the lesson on API responses.
  • It does not make bad code good. It finds one class of bugs, those about types. Logic errors, wrong formulas and bad design remain your job.
  • It is not required for small scripts. For a 50 line script or a quick prototype, the setup may cost more than it saves.
  • It adds some work. You write more code, and there is a learning curve. The payoff grows with the size of the project and of the team.

Structural typing, briefly

TypeScript checks the shape of values, not their names. If an object has the properties a type needs, it fits, even if you never said it implements that type. This is called structural typing, and it matches how JavaScript is actually written. It means you can add types to an existing code base without rewriting it.

When I would choose it

I use TypeScript for any project that will live longer than a few weeks, any project with more than one developer, and any code that talks to an API or a database. I skip it for throwaway scripts. Most major front-end frameworks and many Node libraries are written in it or ship type definitions, so you meet it whether you plan to or not.

How it fits into the workflow

You write .ts files. The compiler (tsc), or a build tool such as Vite or esbuild, turns them into .js. Then the browser or Node runs the .js. In development, your editor runs the checks continuously. The next lesson sets this up.

Common mistakes

  • Thinking TypeScript runs in the browser. Browsers run JavaScript. TypeScript is compiled first.
  • Expecting runtime protection. A type says what you believe the data is. It does not check the real data.
  • **Using any everywhere to make errors disappear.** That throws away the benefit. We cover any and its safer cousin unknown later.
  • Annotating everything. TypeScript can work out many types by itself. Over-annotation makes code noisy.
  • Treating compiler errors as an enemy. They are the whole point. Read them, since they are usually right.

Try it yourself

  1. Open VS Code, create a file test.ts, and write const age: number = "30";. Read the error message that appears.
  2. Write a function fullName(first: string, last: string): string and call it with a number to see the error.
  3. Take a JavaScript function from one of your older projects and write down, in a comment, what type each parameter should be.
  4. Write two or three sentences on which of your own projects would benefit most from types, and why.
typescript
function totalPrice(price: number, quantity: number): number {
  return price * quantity;
}

console.log(totalPrice(100, 3)); // 300

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account