TSTypeScript
BeginnerLesson 1 of 15

Hello TypeScript & Compiling – TypeScript

Your first program and what the compiler does.

TypeScript files end in .ts. After variables and parameters you write the type with a colon. Everything else is normal JavaScript.

const gruss: string = "Hello TypeScript!";
console.log(gruss);

function verdoppeln(zahl: number): number {
  return zahl * 2;
}
console.log(verdoppeln(21));

The compiler tsc checks the types and turns the code into JavaScript. It stops wrong calls before execution:

verdoppeln("21");
// Error: Argument of type 'string' is not assignable to parameter of type 'number'.

const zahl: number = "five";
// Error: Type 'string' is not assignable to type 'number'.

The generated JavaScript no longer contains any types – they are removed completely (type erasure). That is why types cost nothing at runtime, but they do not check anything there either:

// hallo.js (result of tsc)
const gruss = "Hello TypeScript!";
console.log(gruss);
function verdoppeln(zahl) {
    return zahl * 2;
}
console.log(verdoppeln(21));
WarningA compiler error does not automatically stop tsc from producing JavaScript (unless you use noEmitOnError). The error is a warning to you – treat it like a failing test and fix it.
TipEvery valid JavaScript file is also valid TypeScript. You can migrate step by step: first rename .js to .ts, then add types.