← Back to all tutorials

Explicit Types

How to explicitly declare types for variables, arrays, objects, and union types.

Explicit Types

Sometimes you need to declare a variable's type without assigning a value right away.

Variable Type Declarations

let name: string;
let age: number;
let isLoggedIn: boolean;

name = "Mario";  // ✅
age = 25;        // ✅
age = "thirty";  // ❌ Error

Union Types

Allow a variable to hold more than one type:

let uid: string | number;
uid = "abc123";  // ✅
uid = 123;       // ✅
uid = true;      // ❌ Error

Explicit Array Types

let names: string[] = [];  // initialized
names.push("Mario");       // ✅

let mixed: (string | number)[] = [];
mixed.push("hello");  // ✅
mixed.push(42);        // ✅

Explicit Object Types

let ninja: {
    name: string;
    age: number;
    belt: string;
};

ninja = { name: "Mario", age: 30, belt: "black" };  // ✅
ninja = { name: "Yoshi", age: 25 };  // ❌ missing belt

Key Takeaways

  • Use explicit types when declaring without assigning
  • Union types: string | number for multiple type options
  • Array types: string[] or (string | number)[]
  • Object types can be defined inline with property types