TypeScript: More snippets – code examples
Hello World
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
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 errorThe 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
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
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
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 stringThe type of gruss is inferred from the default value. There are no named arguments – you pass an object with an interface instead.
Function overloading
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
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
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
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
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)
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)
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
{
"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.