Skip to content

Hands‑On Exercise: Converting a Small JS Script to TypeScript

In this exercise, you’ll take a small JavaScript utility function, convert it to TypeScript, and watch how the compiler immediately flags issues that JavaScript would silently ignore. This is the fastest way to understand the value of TypeScript.


Step 1 — Start with a plain JavaScript file

Create a file named sum.js:

// sum.js
function sum(a, b) {
  return a + b
}

console.log(sum(10, 20))
console.log(sum("10", 20))   // This is a bug, but JS won't complain
console.log(sum(10))         // Another bug: missing argument

What happens in JavaScript?

Run it:

node sum.js

You’ll get:

30
1020
NaN

JavaScript:

  • concatenates "10" + 20 into "1020"
  • treats undefined as NaN
  • never warns you about incorrect usage

This is exactly the kind of bug TypeScript is designed to prevent.


Step 2 — Convert the file to TypeScript

Rename the file:

sum.js → sum.ts

Now TypeScript will analyze it.


Step 3 — Run the TypeScript compiler

If you installed TypeScript locally:

npx tsc sum.ts

If installed globally:

tsc sum.ts

Step 4 — Observe the compiler feedback

You should see errors like:

Argument of type 'string' is not assignable to parameter of type 'number'.
An argument for 'b' was not provided.

TypeScript immediately catches:

  • passing a string instead of a number
  • missing arguments
  • incorrect function usage

These are bugs that JavaScript would happily run with.


Step 5 — Add explicit types

Update sum.ts:

function sum(a: number, b: number): number {
  return a + b
}

console.log(sum(10, 20))
console.log(sum("10", 20))   // ❌ Type error
console.log(sum(10))         // ❌ Type error

Run the compiler again:

npx tsc sum.ts

Now the errors are even clearer and more precise.


Step 6 — Fix the incorrect calls

Correct the usage:

console.log(sum(10, 20))
console.log(sum(Number("10"), 20))
console.log(sum(10, 0))

Compile again:

npx tsc sum.ts

No errors. The code is now safe and predictable.


Step 7 — Compare the JavaScript output

TypeScript compiles to:

"use strict";
function sum(a, b) {
    return a + b;
}
console.log(sum(10, 20));
console.log(sum(Number("10"), 20));
console.log(sum(10, 0));

Notice:

  • The runtime code is still plain JavaScript
  • TypeScript adds zero runtime overhead
  • All safety comes from compile‑time checks

What You Learned

This tiny exercise demonstrates the core value of TypeScript:

1. TypeScript catches bugs early

  • wrong argument types
  • missing parameters
  • incorrect function usage

2. TypeScript forces clarity

You must define what your function expects and returns.

3. TypeScript improves maintainability

The compiler becomes your first line of defense.

4. TypeScript compiles to plain JavaScript

No runtime cost, no special environment.