TypeScript: Running TypeScript code

Now let’s try running this code.

I’ll use Bun, which has built-in support for TypeScript.

Write this in a test.ts file:

const multiply = (a: number, b: number): number => {
  return a * b

console.log(multiply(4, 2))

Run bun test.js and you’ll see the output 8 in the terminal:

What if we had a type error in our code?

Bun will happily run the code, as if it was JavaScript.

This is because Bun does not type check before execution.

To do that, we must use the TypeScript compiler.

Install typescript in the project:

bun i -D typescript

Then run

bun tsc test.ts

tsc is the TypeScript compiler.

It’s up to you now to go and fix the problem, and recompile:

The compilation created a corresponding .js file that is the compiled JavaScript that browsers will be able to understand:

Lessons in this unit:

0: Introduction
1: Your first TypeScript program
2: Types
3: Typing functions
4: The editor helps you with type errors
5: ▶︎ Running TypeScript code
6: Valid types
7: Type aliases and interfaces
8: Union types
9: Typing arrays with generics
10: The DX of editing TypeScript
11: There's more...
Want to learn more? Check out our courses