Menu
Courses / TypeScript Basics / basic types

basic types

02 / 10 Part of TypeScript Basics

Type Annotations


In TypeScript, you can explicitly declare the type of a variable using a colon followed by the type name.


let age: number = 25;
let username: string = "Alice";
let isActive: boolean = true;


The Core Primitive Types



   
   
       
       
       
       
       
   
TypeExampleDescription
stringlet name: string = "Sam";Textual data, single or double quotes
numberlet price: number = 19.99;All numbers — no separate int/float like Java
booleanlet done: boolean = false;True or false values
nulllet empty: null = null;Represents intentional absence of a value
undefinedlet notSet: undefined = undefined;A variable that hasn't been assigned yet


Type Inference


You don't always have to write the type explicitly — TypeScript is smart enough to infer it from the assigned value.


let city = "Paris"; // inferred as string automatically
city = 42;           // Error: Type 'number' is not assignable to type 'string'


    Best practice: Let inference handle simple, obvious cases. Add explicit annotations for function parameters, return types, and anywhere the type isn't immediately obvious.


Arrays


let scores: number[] = [85, 90, 78];
let names: string[] = ["Alice", "Bob", "Charlie"];

// alternative generic syntax:
let ids: Array = [1, 2, 3];


The any Type


any disables type checking entirely for that variable — it can hold anything, and TypeScript won't complain.


let data: any = 5;
data = "now a string";
data = true; // all perfectly legal


    Warning: Overusing any defeats the whole purpose of TypeScript. Use it sparingly, mainly when working with untyped third-party code.


The unknown Type


A safer alternative to any. You can assign anything to it, but you must narrow its type before using it.


let value: unknown = "hello";

if (typeof value === "string") {
    console.log(value.toUpperCase()); // safe, TypeScript knows it's a string here
}


The void Type


Used for functions that don't return a value.


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


Union Types


A variable can be allowed to hold more than one type using the pipe | symbol.


let id: string | number;
id = 101;      // valid
id = "abc123"; // also valid
id = true;     // Error: boolean not allowed


Literal Types


You can restrict a variable to a specific, exact set of values.


let direction: "up" | "down" | "left" | "right";
direction = "up";    // valid
direction = "sideways"; // Error


Type Aliases for Readability


type ID = string | number;

let userId: ID = 42;
let orderId: ID = "ORD-2024";



    Coming up next: Functions — how TypeScript lets you strictly define what goes in and what comes out.