Primitive Types & Annotations
TypeScript adds static types to JavaScript. Type annotations explicitly declare what type a variable, parameter, or return value should be. TypeScript catches type errors at compile time — before your code runs — preventing entire categories of bugs that JavaScript allows.
35 min•By Priygop Team•Last updated: Feb 2026
TypeScript Primitive Types
- string — Text values: let name: string = 'Alice'. Template literals are also strings
- number — All numbers (int/float): let age: number = 25. No separate int/float types like Java
- boolean — true/false: let isActive: boolean = true. Not truthy/falsy values — strictly boolean
- null / undefined — Distinct types. Enable strictNullChecks (default in strict mode) to catch null errors
- any — Disables type checking. Avoid using any — it defeats the purpose of TypeScript
- unknown — Type-safe alternative to any. Must narrow with typeof/instanceof before using
- void — Functions that don't return a value: function log(msg: string): void { }
- never — Functions that never return: function throwError(): never { throw new Error(); }
Type Annotations Code
Example
// Primitive type annotations
let username: string = "Alice";
let age: number = 25;
let isStudent: boolean = true;
let nothing: null = null;
let notDefined: undefined = undefined;
// Type inference — TypeScript infers the type from the value
let city = "New York"; // inferred as string
let score = 95; // inferred as number
let isValid = true; // inferred as boolean
// No annotation needed when TypeScript can infer!
// Arrays
let numbers: number[] = [1, 2, 3, 4, 5];
let names: string[] = ["Alice", "Bob"];
let mixed: (string | number)[] = ["hello", 42];
// Alternative array syntax
let scores: Array<number> = [90, 85, 92];
// Tuples — fixed-length, typed arrays
let user: [string, number] = ["Alice", 25];
let coordinate: [number, number, number] = [40.7, -74.0, 10];
// user[0] is string, user[1] is number — TypeScript knows!
// Enums — named constants
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}
let move: Direction = Direction.Up;
// const enums — inlined at compile time (smaller output)
const enum HttpStatus {
OK = 200,
NotFound = 404,
ServerError = 500
}
// Function type annotations
function add(a: number, b: number): number {
return a + b;
}
// Arrow function with types
const greet = (name: string): string => `Hello, ${name}!`;
// Optional parameters
function createUser(name: string, age?: number): string {
return age ? `${name}, age ${age}` : name;
}
// Default parameters
function paginate(page: number = 1, limit: number = 10): void {
console.log(`Page ${page}, showing ${limit} items`);
}