~/hackweb.dev
TypeScript Type Annotations
Quiz
...

TypeScript Type Annotations

beginner · updated Tue Sep 08 2026Contribute

Master type annotations for variables, functions, and arrays.

TypeScript Type Annotations

Type annotations explicitly tell TypeScript what type a value should be.

Basic Syntax

Use a colon after the variable name to specify the type:

let name: string = "John";
let age: number = 25;
let isActive: boolean = true;

Tip: TypeScript can infer types automatically — annotations are optional when the type is obvious.

Primitive Types

TypeScript supports all JavaScript primitives:

let name: string = "John";
let age: number = 25;
let isActive: boolean = true;
let nothing: null = null;
let missing: undefined = undefined;
let bigNum: bigint = 9007199254740991n;
let symbol: symbol = Symbol("id");

The any Type

any opts a value out of type checking:

let value: any = "Hello";
value = 42;   // OK
value = true; // OK

Remember: Only use any when migrating legacy code or dealing with truly unknown data.

The unknown Type

unknown is the type-safe alternative to any:

let value: unknown = "Hello";
// let str: string = value; // Error — must narrow first

if (typeof value === "string") {
  console.log(value.toUpperCase()); // OK after narrowing
}

Tip: Prefer unknown over any — it forces you to check the type.

void and never

void = no return value. never = function never returns.

function logMessage(msg: string): void {
  console.log(msg);
}

function throwError(msg: string): never {
  throw new Error(msg);
}

Array Types

Two syntaxes for typed arrays:

let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["Alice", "Bob"];

// Readonly arrays
let fixed: readonly number[] = [1, 2, 3];
// fixed.push(4); // Error

Tuple Types

Tuples have fixed types per position:

let person: [string, number] = ["John", 25];
console.log(person[0].toUpperCase()); // "JOHN"
// person[1].toUpperCase(); // Error: number has no toUpperCase

Why tuples? For data with a fixed structure like coordinates or database rows.

Best Practices

  • Avoid any — use unknown or specific types
  • Always annotate function parameters and return types
  • Use readonly for arrays that shouldn’t be modified
  • Let TypeScript infer when the type is obvious

Common Mistakes

  • Using any excessively
  • Not annotating function return types
  • Forgetting null and undefined are different types in strict mode
  • let arr = [] infers any[] — always give empty arrays a type