Code of the Day
BeginnerLanguage basics

TypeScript basics

Add a type layer to JavaScript that catches mistakes before you run.

JavaScript / TSBeginner9 min read
Recommended first
By the end of this lesson you will be able to:
  • Annotate variables and functions with types
  • Describe object shapes with interfaces and type aliases
  • Explain that TypeScript checks at build time and compiles to JavaScript

is JavaScript with a type layer. You add annotations describing the types you expect; a checker verifies them before the code runs and then compiles plain JavaScript. It brings the static-typing safety from the data-and-types fundamentals lesson to the JS world — and it's the default for serious codebases.

Annotating values and functions

Add : type to variables, parameters, and return values:

let count: number = 0;
const name: string = "Ada";

function greet(person: string, times: number = 1): string {
  return (person + " ").repeat(times).trim();
}

Often you can omit annotations on variables — TypeScript infers the type from the value (let count = 0 is already number). Annotate function parameters and public boundaries; let inference handle the obvious cases.

Describing object shapes

Use an (or type) to describe the shape of an object:

interface User {
  name: string;
  born: number;
  role?: string;   // the ? makes it optional
}

function describe(user: User): string {
  return user.name + " (" + user.born + ")";
}

Now passing an object missing name, or with born as a string, is an error the checker catches immediately — not a runtime surprise.

Union types and safety

A union says "one of these types," which forces you to handle each case:

function format(id: string | number): string {
  return "ID-" + id;
}

TypeScript is especially good at modelling "a value, or nothing" with Type | undefined, nudging you to handle the missing case the data-and-types lesson warned about.

Checked at build, then erased

The key mental model: TypeScript types exist only at development/build time. The compiler checks them, reports errors in your editor, then strips them out, emitting ordinary JavaScript that runs anywhere. The types are a safety net for you and your tools, not a runtime feature.

Because types are erased, they can't be run in the in-browser sandbox here — but everything you've learned about JavaScript values still applies. TypeScript only adds a layer of checking on top.

Where to go next

That completes Language basics. The intermediate The runtime module goes deeper: promises, closures, classes, error handling, and talking to APIs.

Finished reading? Mark it complete to track your progress.

On this page