TSTypeScript

TypeScript: More snippets – code examples

Contents

Hello World

Basics#console#output#stringCompare in all languages
Use case: A first test of whether the compiler and runtime environment work.
const gruss: string = "Hello World!";
console.log(gruss);

Like JavaScript, only with the type annotation : string after the name. tsc compiles, node runs the result.

Variables and Types

Basics#const#let#type#inferenceCompare in all languages
Use case: Store values and catch type errors early in the process.
const name: string = "Ada";
let alter: number = 36;
alter += 1;
const groesse = 1.68;          // type is inferred as number
const aktiv: boolean = true;
console.log(name, alter, groesse, aktiv);
console.log(typeof alter, typeof groesse, typeof aktiv);
// alter = "alt";              // compiler error

The types exist only in the source code – typeof returns JavaScript type names at runtime. With an initial value the type can usually be omitted.

if / else if / else

Control flow#if#conditionCompare in all languages
Use case: React differently, e.g. compute grades or price tiers.
const punkte: number = 73;
if (punkte >= 90) {
  console.log("very good");
} else if (punkte >= 70) {
  console.log("good");
} else {
  console.log("needs improvement");
}

Branching is identical to JavaScript; TypeScript additionally narrows types inside the branches (narrowing).

for and for...of loops

Control flow#for#loop#ofCompare in all languages
Use case: Process every element of a list or repeat n times.
for (let i = 0; i < 3; i++) {
  console.log("Round", i);
}

const fruechte: string[] = ["Apple", "Pear"];
for (const frucht of fruechte) {
  console.log(frucht.toUpperCase());
}

frucht automatically has the type string, so the editor offers string methods.

Function with default value

Functions#function#return#parameterCompare in all languages
Use case: Bundle recurring logic, e.g. greeting texts or calculations.
function begruesse(name: string, gruss = "Hello"): string {
  return gruss + ", " + name + "!";
}

console.log(begruesse("Ada"));
console.log(begruesse("Linus", "Hi"));
// begruesse(42);   // compiler error: number is not string

The type of gruss is inferred from the default value. There are no named arguments – you pass an object with an interface instead.

Function overloading

Functions#overload#function
Use case: A function whose return type depends on the argument type (parse, get, query).
function parse(wert: string): number;
function parse(wert: string[]): number[];
function parse(wert: string | string[]): number | number[] {
  return Array.isArray(wert) ? wert.map(Number) : Number(wert);
}

const a = parse("42");
const b = parse(["1", "2"]);
console.log(a, b);

The first two lines are the visible signatures, the third is the implementation (invisible from the outside). a is number, b is number[].

Working with arrays

Data structures#array#list#map#filter#sortCompare in all languages
Use case: Manage collections of values: add, sort, filter.
const zahlen: number[] = [5, 3, 8, 1];
zahlen.push(10);
zahlen.sort((a, b) => a - b);
console.log(zahlen);
console.log(zahlen.filter((z) => z > 3).map((z) => z * 2));
console.log(zahlen.reduce((s, z) => s + z, 0), Math.max(...zahlen), zahlen.length);

number[] prevents a string from ending up in the array; the callback parameter types are inferred.

Record as a dictionary

Data structures#record#dictionary#map#entriesCompare in all languages
Use case: Store mappings, e.g. configurations or JSON-like data.
const person: Record<string, string | number> = { name: "Ada", alter: 36 };
person.stadt = "London";
for (const [schluessel, wert] of Object.entries(person)) {
  console.log(schluessel, "=", wert);
}
console.log(person.email ?? "no email");

Record<string, ...> describes an object with arbitrary keys. With noUncheckedIndexedAccess, person.email is typed as possibly undefined – which fits ??. For keys of any type there is Map<K, V>.

Class with inheritance

OOP#class#oop#extends#overrideCompare in all languages
Use case: Bundle data and behavior, e.g. users, products, game characters.
class Tier {
  constructor(protected name: string) {}
  sprich(): string {
    return this.name + " makes a sound";
  }
}

class Hund extends Tier {
  override sprich(): string {
    return this.name + " says Woof!";
  }
}

console.log(new Hund("Rex").sprich());

protected name in the constructor creates the field (parameter property). override makes sure the base class really has the method.

Abstract class and interface

OOP#abstract#class#private
Use case: Define shared behavior and force subclasses to implement it.
abstract class Form {
  abstract flaeche(): number;
  beschreibe(): string {
    return "Area: " + this.flaeche().toFixed(2);
  }
}

class Quadrat extends Form {
  constructor(private seite: number) {
    super();
  }
  flaeche(): number {
    return this.seite ** 2;
  }
}

// new Form();   // compiler error: abstract class
console.log(new Quadrat(3).beschreibe());

Every concrete subclass must implement the abstract method; the base class already uses it in beschreibe. Interfaces (implements), by contrast, describe pure contracts.

Read and write a file (Node.js)

Files#fs#file#nodeCompare in all languages
Use case: Save and load logs, configurations or text data.
import { readFileSync, writeFileSync } from "node:fs";

writeFileSync("notizen.txt", "Line 1\nLine 2\n", "utf-8");
const text: string = readFileSync("notizen.txt", "utf-8");
for (const zeile of text.split("\n")) {
  if (zeile) console.log(zeile);
}

Requires npm install --save-dev @types/node so that TypeScript knows the types of node:fs. Because of the "utf-8" argument, readFileSync returns a string (otherwise a Buffer).

Typed API request (fetch)

Networking#fetch#async#promise#api
Use case: Load data from a web API and process it further in code using types.
interface Repo {
  full_name: string;
  stargazers_count: number;
}

async function ladeRepo(name: string): Promise<Repo> {
  const antwort = await fetch("https://api.github.com/repos/" + name);
  if (!antwort.ok) throw new Error("HTTP " + antwort.status);
  return (await antwort.json()) as Repo;
}

const repo = await ladeRepo("microsoft/TypeScript");
console.log(repo.full_name, repo.stargazers_count);

as Repo is only an assertion – the response is not checked. In production code you validate it (type guard, Zod). Top-level await needs an ES module.

tsconfig.json for a Node project

Tooling#tsconfig#strict#compiler
Use case: Start a new project with strict but practical compiler settings.
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitOverride": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "outDir": "dist",
    "rootDir": "src"
  },
  "include": ["src"]
}

strict enables the most important checks; noUncheckedIndexedAccess makes array/index accesses safe. Compile with npx tsc, only check with npx tsc --noEmit.