Variables in TypeScript

In TypeScript, variables are explicitly declared and used by the compiler to check type-correctness of function calls.

// Variables can be declared using 'let' or 'const'
let a = "initial";
console.log(a);

// You can declare multiple variables at once
let b: number = 1, c: number = 2;
console.log(b, c);

// TypeScript will infer the type of initialized variables
let d = true;
console.log(d);

// Variables declared without initialization are undefined
let e: number;
console.log(e);

// The 'const' keyword is used for variables that won't be reassigned
const f = "apple";
console.log(f);

To run this TypeScript code, you need to compile it to JavaScript first:

$ tsc variables.ts
$ node variables.js
initial
1 2
true
undefined
apple

In TypeScript:

  1. Variables are typically declared using let or const.
  2. Type annotations are optional but can be added for clarity.
  3. TypeScript has type inference, so it can deduce types from initialized variables.
  4. Variables declared without initialization are undefined, not zero-valued.
  5. The const keyword is used for variables that won’t be reassigned, similar to := in some cases.

TypeScript provides more flexibility in variable declarations compared to statically typed languages, while still offering strong type checking.