TypeScript Basic Types
Annotate primitives, arrays, tuples, and any with TypeScript types
Overview
TypeScript adds static types to JavaScript. Types are checked at compile time and erased at runtime. Start with primitives and collections, then layer functions and objects as your codebase grows.
Syntax / Usage
let name: string = 'Ada'
let age: number = 36
let active: boolean = true
const ids: number[] = [1, 2, 3]
const tags: Array<string> = ['ts', 'web']
// Tuple — fixed length and types
const point: [number, number] = [10, 20]
// any disables checking (avoid when possible)
let legacy: any = 'anything'
// unknown — safer than any; narrow before use
let input: unknown = getInput()
if (typeof input === 'string') {
console.log(input.toUpperCase())
}
// void and never
function log(msg: string): void {
console.log(msg)
}
Examples
Function with typed parameters and return:
function formatPrice(amount: number, currency = 'USD'): string {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency,
}).format(amount)
}
Readonly arrays:
const ROLES: readonly string[] = ['admin', 'user']
// ROLES.push('guest') — error
Common Mistakes
- Overusing
any, defeating TypeScript's purpose - Assuming runtime validation—types disappear after compilation
- Using
objectwhen a specific shape is known—prefer interfaces - Confusing
nullandundefinedwithoutstrictNullChecks
See Also
interfaces unions type-guards generics