TSTypeScript
BeginnerLesson 2 of 15

Basic Types & Type Inference – TypeScript

string, number, boolean, arrays, tuples, any and unknown.

The primitive types are called string, number and boolean, plus bigint, symbol, null and undefined. Most of the time you do not have to write the type at all: TypeScript infers it from the value (type inference).

const name: string = "Ada";
let alter: number = 36;
let aktiv = true;            // inferred: boolean
let groesse = 1.68;          // inferred: number

alter = 37;
// alter = "alt";            // Error: string is not number
// aktiv = 1;                // Error: number is not boolean

You write arrays as Type[]; tuples are fixed-length arrays with a fixed type per position:

const zahlen: number[] = [1, 2, 3];
const namen: Array<string> = ["Ada", "Linus"];   // equivalent to string[]
zahlen.push(4);
// zahlen.push("five");      // Error

const punkt: [number, number] = [3, 4];
const eintrag: [string, number] = ["Ada", 36];
const [wer, wieAlt] = eintrag;
console.log(punkt[0], wer, wieAlt);

The two escape-hatch types: any turns off type checking for a value completely – convenient, but dangerous. unknown means "some value" that you must check first before you use it.

let a: any = "text";
a.gibtEsNicht();             // no compiler error – crash only at runtime!

let u: unknown = "text";
// u.toUpperCase();          // Error: 'u' is of type 'unknown'
if (typeof u === "string") {
  console.log(u.toUpperCase());   // here TypeScript knows: string
}

Other special types: void (function without a return value), never (never returns, e.g. always throws an error), as well as null and undefined as types of their own.

WarningAvoid any. Every any is a hole in the type system through which errors sneak in. If you do not know the type (yet), use unknown and narrow it down.
TipDo not write redundant type annotations on variables with an initial value. Annotations are mainly needed for function parameters, return values of public functions and empty initial values (const liste: string[] = [];).