Basic Types
string, number, boolean, null, undefined, any, unknown, void, never
Skills taught: ts.string, ts.number, ts.boolean, ts.null-undefined, ts.any, ts.unknown, ts.void, ts.never
Primitive types
// Primitive types
let username: string = 'Alice';
let age: number = 30;
let isAdmin: boolean = false;
let nothing: null = null;
let missing: undefined = undefined;
// TypeScript infers from literals — annotations optional here
const PI = 3.14159; // inferred: number
const APP = 'KERNAL'; // inferred: string
// Template literal types (TS 4.1+)
type EventName = `on${string}`; // 'onClick', 'onSubmit', etc.
const handler: EventName = 'onClick';
// Literal types — only specific values allowed
type Direction = 'left' | 'right' | 'up' | 'down';
let dir: Direction = 'left';
// dir = 'diagonal'; // Error: not assignable to type Direction
// bigint — large integers
const big: bigint = 9999999999999999n;
any, unknown, void, never
// any — opt out of type checking (avoid!)
let data: any = 'hello';
data = 42; // OK — any accepts anything
data.toUpperCase(); // OK at compile time — but crashes if data is a number!
// unknown — safe version of any (prefer this)
let value: unknown = 'hello';
// value.toUpperCase(); // Error: can't use unknown without checking type first
if (typeof value === 'string') {
console.log(value.toUpperCase()); // OK — narrowed to string
}
// void — function returns nothing
function logMessage(msg: string): void {
console.log(msg);
// return 42; // Error: can't return a value from void function
}
// never — function never returns (throws or loops forever)
function fail(msg: string): never {
throw new Error(msg);
}
// never for exhaustive checks
type Status = 'active' | 'inactive';
function describe(s: Status): string {
if (s === 'active') return 'User is active';
if (s === 'inactive') return 'User is inactive';
const _exhaustive: never = s; // Error if Status gains a new variant
return _exhaustive;
}
Frequently Asked Questions
What does strictNullChecks do?
With strictNullChecks (on by default with strict: true), null and undefined are their own types — they can't be assigned to string, number, etc. This prevents a huge category of 'Cannot read property of null' runtime errors. To allow null: use string | null. This is the single most impactful TypeScript setting.