BeginnerTypeScript · Lesson 2 of 7

Variables & Basic Types

let vs const, primitive types, type inference, arrays and any vs unknown.

Use const for values that never get reassigned and let for values that change. Avoid var — it has confusing scoping rules.

The basic (primitive) types are string, number (integers and decimals), boolean, null and undefined. You can annotate a variable with : type, but TypeScript usually infers the type from the value, so annotations are mostly needed for function parameters and empty values.

Arrays are written number[] or Array<number>. A tuple like [string, number] is a fixed-length array where each position has its own type.

any switches type checking off — avoid it. When you truly don't know a value's type (for example, parsed JSON), use unknown, which forces you to check the type before using it.

types.tsTypeScript
const school = "Azania Secondary"; // inferred as string
let students = 420;                 // inferred as number
students = students + 15;           // OK: let can change

const isOpen: boolean = true;
const scores: number[] = [78, 64, 91];
const subjects: string[] = ["Maths", "Physics"];
const pair: [string, number] = ["Biology", 85]; // tuple

let nickname: string | undefined; // no value yet
nickname = "Doli";

const raw: unknown = JSON.parse('{"marks": 72}');
if (typeof raw === "object" && raw !== null && "marks" in raw) {
  console.log("Parsed:", raw.marks);
}

console.log(school, students, isOpen, scores, subjects, pair, nickname);

Key points

  • Prefer const; use let only when a value must change.
  • Let TypeScript infer types where it can; annotate parameters and empty values.
  • Use unknown instead of any, then narrow it with checks like typeof.

Exercise

Create an array of five test scores, then compute and print the total and average. Store a student's name and average together in a tuple [string, number].

Show solution

Try the exercise yourself first — then compare your approach with this one.

Use reduce (or a loop) to add the scores, divide by the array's length for the average, and store the result in a tuple whose two positions have different types.

scores.tsTypeScript
const scores: number[] = [78, 64, 91, 55, 82];

let total = 0;
for (const s of scores) total += s;
const average = total / scores.length;

const record: [string, number] = ["Amina", average];

console.log("Total:", total);                     // Total: 370
console.log("Average:", average.toFixed(1));     // Average: 74.0
console.log(record[0] + " averaged " + record[1]); // Amina averaged 74

Check your understanding

  1. Which declaration should you use for a value that never gets reassigned?

  2. What type does TypeScript infer for let students = 420;?

  3. Why prefer unknown over any for data of uncertain shape?

  4. What is [string, number]?

Ask AI