TypeScript for JavaScript Developers: Your First Hour

Install TypeScript, compile your first .ts file and read real tsc errors: types, inference, interfaces, unions, narrowing, strict mode and tsconfig.json.

AAyim Nelson27 Nov 20267 min read3

You know JavaScript. You can write functions, loop over arrays and change a page when someone clicks a button. Then you open a job advert or a real project, and it says TypeScript. Is it a whole new language to learn?

Not really. TypeScript is JavaScript with types added: you say what kind of value something is, and a checker warns you, before the code runs, when you use it the wrong way. Everything you already know still works. Give it one hour, and this guide will get you writing it.

The bug TypeScript is built to catch

Here's a top-up calculator in plain JavaScript. The balance came from a form field, so it's a string:

const balance = "20";   // came from a form field, so it's a string
const topUp = 5;

console.log(balance + topUp);
console.log(balance * 2);

Run it with node topup.js:

205
40

A balance of GHS 205 instead of GHS 25. + joined the two as text, while * quietly turned the string into a number. JavaScript didn't complain at all, so this kind of bug reaches real users. TypeScript would refuse to let a string sit where a number belongs.

Install TypeScript

You need Node.js. In your project folder, add TypeScript as a dev dependency (we pin a version, as you would in a real project):

npm install --save-dev typescript@7.0.2
npx tsc --version

The second command prints:

Version 7.0.2

tsc is the TypeScript compiler. TypeScript 7 is a rewrite of the compiler in Go, so it is much faster than older versions, but the language and the error messages are the same. (Newer versions of npm also print a couple of npm notice lines before the output; we've left those out here.)

Your first .ts file

TypeScript files end in .ts. Create bundle.ts. A colon after a name gives its type:

const pricePerGb: number = 10;
const plan: string = "Weekly";

function bundleCost(price: number, gigabytes: number): number {
  return price * gigabytes;
}

console.log(`${plan} bundle, 3 GB: GHS ${bundleCost(pricePerGb, 3)}`);

(price: number, gigabytes: number): number says the function takes two numbers and returns a number. Compile it:

npx tsc bundle.ts

No output means no errors. tsc has written bundle.js next to it, which is the same code with the types taken out:

"use strict";
const pricePerGb = 10;
const plan = "Weekly";
function bundleCost(price, gigabytes) {
    return price * gigabytes;
}
console.log(`${plan} bundle, 3 GB: GHS ${bundleCost(pricePerGb, 3)}`);

Run it as normal with node bundle.js:

Weekly bundle, 3 GB: GHS 30

That's the key idea: the types exist only to be checked. Browsers and Node.js run the plain JavaScript that's left.

Let tsc find your mistakes

Now the useful part. This file, mistakes.ts, has three bugs:

const pricePerGb: number = 10;
const gigabytes: number = "3";

function bundleCost(price: number, gb: number): number {
  return price * gb;
}

console.log(bundleCost(pricePerGb));
console.log(pricePerGb.toUppercase());

--noEmit means "only check, don't write a .js file":

npx tsc --noEmit mistakes.ts
mistakes.ts(2,7): error TS2322: Type 'string' is not assignable to type 'number'.
mistakes.ts(8,13): error TS2554: Expected 2 arguments, but got 1.
mistakes.ts(9,24): error TS2339: Property 'toUppercase' does not exist on type 'number'.

Each line gives the file, the (line,column), an error code and a plain message: a string where a number belongs, a missing argument, and a method numbers don't have. Not one line of the program ran. In VS Code you don't even need the command: the editor runs the same checks and underlines mistakes as you type.

You don't have to write every type

When you give a variable a value, TypeScript infers its type:

let town = "Kumasi";
town = 233;

const balances = [25, 40, 12.5];
balances.push("ten");
infer.ts(2,1): error TS2322: Type 'number' is not assignable to type 'string'.
infer.ts(5,15): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

No annotations at all, yet TypeScript knew town is a string and balances is an array of numbers. A good habit: write types for function parameters, and let inference handle most variables.

Describe your objects with interfaces

An interface names the shape of an object. A ? makes a property optional. A union type, written with |, means "one of these":

interface Payment {
  phone: string;
  amount: number;
  note?: string;
}

const rent: Payment = { phone: "0241234567", amount: 450, note: "November rent" };
const lunch: Payment = { phone: "0201234567" };
const fees: Payment = { phone: "0551234567", amount: 900, refrence: "JHS 2" };

type PaymentState = "pending" | "sent" | "failed";

let state: PaymentState = "pending";
state = "sent";
state = "done";
payment.ts(8,7): error TS2741: Property 'amount' is missing in type '{ phone: string; }' but required in type 'Payment'.
payment.ts(9,59): error TS2353: Object literal may only specify known properties, and 'refrence' does not exist in type 'Payment'.
payment.ts(15,1): error TS2322: Type '"done"' is not assignable to type 'PaymentState'.

A mobile money payment with no amount, a misspelt property name and a state the app doesn't know about: all caught. rent passes, and it would pass without its note too, because that property is optional.

Values that might be missing

number | null means "a number, or nothing yet", for example a balance that hasn't loaded. TypeScript won't let you use it as a number until you've checked:

function balanceText(balance: number | null): string {
  return `GHS ${balance.toFixed(2)}`;
}
narrow.ts(2,17): error TS18047: 'balance' is possibly 'null'.

Add the check, and the error goes away:

function balanceText(balance: number | null): string {
  if (balance === null) {
    return "Balance not loaded yet";
  }
  return `GHS ${balance.toFixed(2)}`;
}

After the if, TypeScript knows balance must be a number. This is called narrowing, and it removes a whole family of "cannot read properties of null" crashes.

Strict mode is on by default

TypeScript's strict setting turns on its most useful checks, and since TypeScript 6 it is on by default. Here, a parameter with no type and a search that may find nothing:

function addFee(amount) {
  return amount + 0.5;
}

const towns = ["Accra", "Kumasi", "Tamale"];
const found = towns.find((t) => t === "Ho");
console.log(found.toUpperCase());
strict.ts(1,17): error TS7006: Parameter 'amount' implicitly has an 'any' type.
strict.ts(7,13): error TS18048: 'found' is possibly 'undefined'.

Ho isn't in the list, so find returns undefined and this program really would crash. Run the same check with --strict false and tsc prints nothing at all. Silence isn't safety: keep strict on, and in older projects set "strict": true yourself.

Using TypeScript in a real project

A project keeps its settings in tsconfig.json (npx tsc --init writes a long, commented one). For a Vite project, a short version is enough:

{
  "compilerOptions": {
    "target": "es2022",
    "module": "esnext",
    "moduleResolution": "bundler",
    "strict": true,
    "noEmit": true,
    "skipLibCheck": true
  },
  "include": ["src"]
}

Now plain npx tsc, with no file names, checks every file in src. One thing surprises many people: Vite removes the types but never checks them. That keeps the dev server fast, but a type error won't stop npm run dev. So add a script to package.json, "typecheck": "tsc", and run npm run typecheck before you ship.

What to do with the rest of your day

In one hour you've met annotations, inference, interfaces, unions, narrowing, strict mode and tsconfig.json. That's most of the TypeScript you'll write every day. Next, try converting one small JavaScript file you've already written: rename it to .ts, run npx tsc --noEmit, and fix what it finds.

  • Frontend Tooling: npm, Modules and TypeScript teaches TypeScript the way real projects use it, alongside npm, ES modules, Vite, ESLint, Prettier and environment variables, with real terminal output at every step.
  • JavaScript Crash Course is the place to start if variables, functions, arrays and objects still feel shaky. TypeScript is much easier once JavaScript feels natural.

Comments

Log in to join the conversation.

Loading comments...