Syntax
let name: string;
let age: number;
let isActive: boolean;Examples
Primitive Type Annotations
Explicitly typing variables with the core primitives.
let name: string = "Alice";
let age: number = 25;
let isActive: boolean = true;
// TypeScript catches mismatches immediately
// age = "twenty-five"; // Error: Type 'string' is not assignable to type 'number'
let id: string | number = 101; // union type, can be eitherany vs unknown
unknown is the type-safe alternative to any - it requires a check before you can use the value.
let flexible: any = "hello";
flexible.toUpperCase(); // allowed, no error - any disables checking entirely
flexible = 42; // also allowed, any accepts anything
let safer: unknown = "hello";
// safer.toUpperCase(); // Error - must narrow the type first
if (typeof safer === "string") {
safer.toUpperCase(); // OK now - TypeScript knows it is a string here
}void and never
Types for functions that return nothing, or never return at all.
function logMessage(message: string): void {
console.log(message); // no return statement - return type is void
}
function throwError(message: string): never {
throw new Error(message); // never actually returns - always throws
}
function infiniteLoop(): never {
while (true) { /* never exits */ }
}Best practices
- Prefer unknown over any whenever possible - it forces you to check a value's type before using it, catching bugs any would silently allow
- Let TypeScript infer types where it reasonably can (const age = 25) rather than annotating every single variable - annotate mainly function parameters and return types
- Use never for functions that always throw or never return, which helps TypeScript correctly narrow types in the code that calls them
- Avoid any as a habit - it is sometimes necessary for gradual migration or truly dynamic data, but it opts out of type safety entirely wherever it is used
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook