Intermediate Exercism • typescript

TypeScript Basics

Lesson Overview

Introduction to static typing and the TypeScript compiler.

TypeScript Basics

TypeScript is a superset of JavaScript that adds static typing to the language. This allows you to catch errors at compile-time rather than run-time, making your code more robust and easier to maintain.

Why TypeScript?

JavaScript is a dynamically typed language. This means you can assign a number to a variable and later reassign it to a string without the compiler complaining. While this flexibility is powerful, it often leads to unexpected bugs in large applications.

// JavaScript
let age = 25;
age = "twenty-five"; // No error, but might break something later

In TypeScript, you can explicitly define the type of a variable:

// TypeScript
let age: number = 25;
age = "twenty-five"; // Error: Type 'string' is not assignable to type 'number'.

Basic Types

TypeScript supports several basic types:

  • number: For all numeric values (integers, floats, etc.)
  • string: For textual data.
  • boolean: For true or false values.
  • any: A “catch-all” type that opts out of type checking (use sparingly!).
  • void: Used for functions that don’t return a value.

Type Inference

You don’t always have to explicitly write out the types. TypeScript is smart enough to infer the type based on the initial value you provide.

let message = "Hello, TypeScript!"; // TypeScript infers this is a 'string'
message = 123; // Error: Type 'number' is not assignable to type 'string'.

Compilation

Browsers and Node.js cannot run .ts files directly. You must first compile (or “transpile”) your TypeScript code into standard JavaScript using the TypeScript Compiler (tsc).

tsc my-code.ts

This generates a my-code.js file that you can then run in any JavaScript environment.