Skip to content
TypeScript Essentials

TypeScript Basic Types

Beginner Lesson 3 of 9

TypeScript provides static typing through type annotations.

// String
let firstName: string = "John";
// Number
let age: number = 25;
let price: number = 99.99;
// Boolean
let isActive: boolean = true;
// Null and Undefined
let nothing: null = null;
let notDefined: undefined = undefined;
// Symbol
let sym: symbol = Symbol("key");
// BigInt
let big: bigint = 100n;
// Array of numbers
let numbers: number[] = [1, 2, 3];
// Generic syntax
let names: Array<string> = ["Alice", "Bob"];
// Mixed arrays (avoid if possible)
let mixed: (string | number)[] = [1, "two", 3];
// Readonly arrays
let readOnly: readonly number[] = [1, 2, 3];
// Fixed-length array with specific types
let person: [string, number] = ["Alice", 25];
// Named tuples (TypeScript 4.0+)
let user: [name: string, age: number] = ["Bob", 30];
// Optional elements
let optional: [string, number?] = ["Alice"];
// Numeric enum
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right // 3
}
// String enum
enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE",
Pending = "PENDING"
}
// Usage
let dir: Direction = Direction.Up;
// Any - avoid when possible
let anything: any = "string";
anything = 42;
anything = true;
// Unknown - safer than any
let value: unknown = "hello";
if (typeof value === "string") {
console.log(value.toUpperCase());
}
// Void - no return value
function log(msg: string): void {
console.log(msg);
}
// Never - never returns
function error(msg: string): never {
throw new Error(msg);
}
// Angle bracket syntax
let value: unknown = "hello";
let length: number = (<string>value).length;
// as syntax (preferred in JSX)
let length2: number = (value as string).length;
// Non-null assertion
let el = document.getElementById("app")!;

Continue to Interfaces →