TypeScript Cheat Sheet: Types, Generics, Utility Types, Narrowing and tsconfig
typescript-cheatsheet is a compact, example-first TypeScript reference for developers who already know JavaScript. It covers basic and advanced types, interfaces vs type aliases, generics, narrowing and type guards, every built-in utility type, mapped, conditional and template literal types, classes, modules, declaration files, tsconfig.json settings for Node.js, bundlers and libraries, and the changes in TypeScript 6.0 and the native TypeScript 7.0 compiler.
Every non-trivial snippet has a type-checked version in examples/, including compile-time tests (Expect<Equal<...>>) that fail the build if a type is wrong.
Last reviewed: December 2026, against TypeScript 7.0.2 (
npm view typescript version). Examples are checked withtsc7.0 and run with Node.js type stripping.
npm install
npm run check # tsc (type-check) + node --test (runtime tests)
Table of Contents
- Basic Types
- Arrays and Tuples
- Objects, Interfaces and Type Aliases
- Unions, Intersections and Literal Types
- Functions
- Narrowing and Type Guards
- Generics
- Utility Types Reference
- keyof, typeof and Indexed Access
- Mapped Types
- Conditional Types and infer
- Template Literal Types
- as const, satisfies and Enums
- Classes
- Modules and Imports
- Declaration Files and Ambient Types
- Patterns: Branded Types, Result, Exhaustive Switch
- tsconfig.json Cheat Sheet
- TypeScript 6.0 and 7.0: What Changed
- Running TypeScript
- Common Errors and Fixes
- Feature Version Table
- Resources
- Validation Libraries
- FAQ
- Where to Go Next
- Contributing
- License
- More free resources
Basic Types
let title: string = 'Hello';
let count: number = 42; // integers and floats
let big: bigint = 9007199254740993n;
let done: boolean = false;
let id: symbol = Symbol('id');
let nothing: null = null;
let missing: undefined = undefined;
let anything: any; // turns type checking off: avoid
let unknownValue: unknown; // safe "anything": must be narrowed before use
function fail(msg: string): never { throw new Error(msg); } // never returns
function log(msg: string): void { console.log(msg); } // returns nothing useful
let obj: object = { a: 1 }; // any non-primitive
Type inference: you rarely need annotations on local variables. Annotate function parameters, public APIs and return types of exported functions.
const n = 1; // type: 1 (const = literal type)
let m = 1; // type: number
const list = [1, 'a'] // type: (string | number)[]
any vs unknown:
const a: any = JSON.parse(text);
a.foo.bar(); // compiles, may crash at run time
const u: unknown = JSON.parse(text);
u.foo; // error: 'u' is of type 'unknown'
if (typeof u === 'object' && u !== null && 'foo' in u) u.foo; // ok after narrowing
Arrays and Tuples
const nums: number[] = [1, 2, 3];
const names: Array<string> = ['a', 'b'];
const ro: readonly number[] = [1, 2]; // or ReadonlyArray<number>
ro.push(3); // error
// Tuples: fixed length, typed positions
const pair: [string, number] = ['age', 30];
const labeled: [name: string, age?: number] = ['Ada']; // labels + optional element
const rest: [string, ...number[]] = ['scores', 1, 2, 3];
const point = [1, 2] as const; // readonly [1, 2]
// Destructuring keeps the types
const [key, value] = pair; // string, number
With noUncheckedIndexedAccess (recommended), nums[5] has type number | undefined, which forces you to handle out-of-range access.
Objects, Interfaces and Type Aliases
interface User {
readonly id: number; // cannot be reassigned
name: string;
email?: string; // optional
[key: `meta_${string}`]: unknown; // index signature with a template pattern
}
type Point = { x: number; y: number };
// Extending
interface Admin extends User { permissions: string[] }
type Point3D = Point & { z: number };
// Index signatures and Record
const scores: { [player: string]: number } = {};
const byId: Record<string, User> = {};
// Methods and call signatures
interface Formatter {
format(value: number): string; // method
(value: number): string; // callable
new (locale: string): Formatter; // constructable
}
interface vs type: which one?
interface |
type |
|
|---|---|---|
| Object shapes | Yes | Yes |
| Unions, tuples, primitives, mapped/conditional types | No | Yes |
extends another type |
extends keyword |
& intersection |
| Declaration merging (reopen and add fields) | Yes | No |
| Error messages and performance | Slightly better for big object hierarchies | Fine |
A simple rule: interface for object shapes others may extend (public APIs), type for everything else. Being consistent matters more than the choice.
Declaration merging example (how libraries let you add fields):
interface Window { myAppVersion: string } // merges into the global Window
Excess property checks apply only to fresh object literals:
const p: Point = { x: 1, y: 2, z: 3 }; // error: 'z' does not exist in type 'Point'
const tmp = { x: 1, y: 2, z: 3 };
const q: Point = tmp; // ok: structural typing, extra props allowed
Optional vs undefined, with exactOptionalPropertyTypes on:
interface Opts { timeout?: number }
const a: Opts = {}; // ok
const b: Opts = { timeout: undefined } // error with exactOptionalPropertyTypes
Unions, Intersections and Literal Types
type Id = string | number; // union: one of
type Direction = 'up' | 'down' | 'left' | 'right'; // string literal union
type Dice = 1 | 2 | 3 | 4 | 5 | 6;
type WithTimestamps<T> = T & { createdAt: Date; updatedAt: Date }; // intersection: all of
function move(dir: Direction) {}
move('up'); // ok
move('north'); // error
On a union you can only use members common to every type until you narrow:
function len(x: string | string[]) {
return x.length; // ok: both have length
// x.toUpperCase(); // error: not on string[]
}
Functions
// Parameter and return types
function add(a: number, b: number): number { return a + b; }
const mul = (a: number, b: number): number => a * b;
// Optional, default and rest parameters
function greet(name: string, greeting = 'Hello', punct?: string): string {
return `${greeting}, ${name}${punct ?? '!'}`;
}
function sum(...nums: number[]): number { return nums.reduce((a, b) => a + b, 0); }
// Function types
type BinaryOp = (a: number, b: number) => number;
type Handler = { (event: string): void; displayName: string };
// Object parameter with destructuring
function createUser({ name, age = 0 }: { name: string; age?: number }) {}
// Overloads: several call signatures, one implementation
function parse(input: string): number;
function parse(input: string[]): number[];
function parse(input: string | string[]): number | number[] {
return Array.isArray(input) ? input.map(Number) : Number(input);
}
const one = parse('1'); // number
const many = parse(['1']); // number[]
// Typing `this`
function onClick(this: HTMLElement, e: MouseEvent) { this.classList.add('clicked'); }
// Async functions return Promise<T>
async function fetchUser(id: number): Promise<User> {
const res = await fetch(`/api/users/${id}`);
return (await res.json()) as User; // json() returns any/unknown: validate in real code
}
// Assertion signatures and type predicates: see Narrowing
void in a function type means “the return value is ignored”, so const f: () => void = () => 42 is allowed. This is why array.forEach(x => list.push(x)) compiles.
Narrowing and Type Guards
TypeScript follows your control flow and narrows a union to the members that are still possible. Full examples: examples/narrowing.ts.
| Technique | Example | Narrows to |
|---|---|---|
typeof |
typeof x === 'string' |
primitives: string, number, bigint, boolean, symbol, undefined, function, object |
| Truthiness | if (x) |
removes null, undefined, '', 0, false (careful with 0 and ‘’) |
| Equality | x === null, x !== undefined |
specific values |
in |
'swim' in animal |
members that have the property |
instanceof |
err instanceof Error |
class instances |
Array.isArray |
Array.isArray(x) |
arrays |
| Discriminant property | shape.kind === 'circle' |
the matching union member |
| Type predicate | function isUser(v: unknown): v is User |
User when true |
| Assertion function | function assert(v): asserts v is T |
T after the call |
Discriminated unions + exhaustive check
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; size: number };
function area(s: Shape): number {
switch (s.kind) {
case 'circle': return Math.PI * s.radius ** 2;
case 'square': return s.size ** 2;
default: {
const unreachable: never = s; // error here if a new kind is not handled
throw new Error(`Unhandled: ${JSON.stringify(unreachable)}`);
}
}
}
Type predicates and assertion functions
function isString(v: unknown): v is string {
return typeof v === 'string';
}
function assertIsDefined<T>(v: T): asserts v is NonNullable<T> {
if (v == null) throw new Error('Expected a value');
}
const el = document.getElementById('app');
assertIsDefined(el);
el.textContent = 'ready'; // el: HTMLElement
Since TypeScript 5.5, simple arrow functions infer predicates themselves:
const ids = [1, undefined, 3].filter((x) => x !== undefined); // number[]
Narrowing gotchas
- Narrowing is reset by function calls for mutable variables and properties in some cases; copy to a
constfirst. - Narrowing does not cross callback boundaries for
letvariables that are reassigned later. typeof null === 'object', so checkx !== nulltoo.
Generics
Generics are type parameters: they let a function or type work over many types while keeping the relationship between inputs and outputs. Examples: examples/generics.ts.
function identity<T>(value: T): T { return value; }
identity('a'); // T inferred as string
identity<number>(1); // explicit
// Constraints
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; }
getProp({ a: 1, b: 'x' }, 'b'); // string
getProp({ a: 1 }, 'z'); // error
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
// Defaults
interface ApiResponse<TData = unknown> { data: TData; status: number }
// Generic types and interfaces
type Maybe<T> = T | null | undefined;
interface Box<T> { value: T; map<U>(fn: (v: T) => U): Box<U> }
// Generic classes
class Stack<T> {
#items: T[] = [];
push(item: T): void { this.#items.push(item); }
pop(): T | undefined { return this.#items.pop(); }
}
// const type parameters (5.0): keep literal types
function routes<const T extends readonly string[]>(paths: T): T { return paths; }
const r = routes(['/a', '/b']); // readonly ['/a', '/b']
// NoInfer (5.4): stop a parameter from influencing inference
function createFSM<S extends string>(states: S[], initial: NoInfer<S>) {}
createFSM(['idle', 'loading'], 'idle'); // ok
createFSM(['idle', 'loading'], 'done'); // error: 'done' not in states
Rules of thumb:
- If a type parameter appears only once, you probably do not need it:
function f<T>(x: T): voidis justfunction f(x: unknown): void. - Let inference work; specify type arguments only when inference cannot see the type (for example
useState<User | null>(null)). - Constrain as little as possible, as much as needed.
Utility Types Reference
Built-in types that transform other types. Compile-time tests for these: examples/advanced-types.ts.
| Utility | Result | Example |
|---|---|---|
Partial<T> |
All properties optional | Update payloads: Partial<User> |
Required<T> |
All properties required | Required<Options> after defaults |
Readonly<T> |
All properties readonly (shallow) | Frozen config |
Record<K, V> |
Object with keys K and values V |
Record<'a' \| 'b', number> |
Pick<T, K> |
Only keys K |
Pick<User, 'id' \| 'name'> |
Omit<T, K> |
All keys except K |
Omit<User, 'password'> |
Exclude<U, M> |
Union members not assignable to M |
Exclude<'a' \| 'b', 'a'> is 'b' |
Extract<U, M> |
Union members assignable to M |
Extract<string \| number, number> is number |
NonNullable<T> |
Removes null and undefined |
NonNullable<string \| null> is string |
ReturnType<F> |
Return type of a function type | ReturnType<typeof setTimeout> |
Parameters<F> |
Parameter tuple | Parameters<typeof fetch>[1] |
ConstructorParameters<C> |
Constructor parameter tuple | ConstructorParameters<typeof Date> |
InstanceType<C> |
Instance type of a class constructor | InstanceType<typeof Map> |
Awaited<T> |
Unwraps promises recursively | Awaited<Promise<Promise<number>>> is number |
NoInfer<T> |
Blocks inference from this position | See Generics |
ThisParameterType<F> |
Type of this param |
|
OmitThisParameter<F> |
Function type without this |
|
ThisType<T> |
Marker for this in object literals (needs noImplicitThis) |
|
Uppercase<S> / Lowercase<S> |
Case conversion of string literal types | Uppercase<'get'> is 'GET' |
Capitalize<S> / Uncapitalize<S> |
First character case | Capitalize<'name'> is 'Name' |
Common combinations:
type CreateUser = Omit<User, 'id' | 'createdAt'>;
type UpdateUser = Partial<Omit<User, 'id'>> & Pick<User, 'id'>;
type UserPreview = Pick<User, 'id' | 'name'>;
type Handlers = Record<Direction, () => void>;
type FetchOptions = NonNullable<Parameters<typeof fetch>[1]>;
type Data = Awaited<ReturnType<typeof loadData>>; // what loadData() resolves to
Omit is not distributive over unions. For a union, write a distributive version:
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
keyof, typeof and Indexed Access
interface User { id: number; name: string; tags: string[] }
type UserKeys = keyof User; // 'id' | 'name' | 'tags'
type NameType = User['name']; // string
type IdOrName = User['id' | 'name']; // number | string
type Tag = User['tags'][number]; // string (element type of an array)
const defaults = { retries: 3, verbose: false };
type Defaults = typeof defaults; // { retries: number; verbose: boolean }
function getConfig() { return { host: 'localhost', port: 5432 }; }
type Config = ReturnType<typeof getConfig>;
const COLORS = ['red', 'green', 'blue'] as const;
type Color = (typeof COLORS)[number]; // 'red' | 'green' | 'blue'
typeof in a type position takes the type of a value. keyof takes the keys of a type. Combine them: keyof typeof obj.
Mapped Types
Create a new object type by looping over keys.
type Optional<T> = { [K in keyof T]?: T[K] }; // same as Partial
type Mutable<T> = { -readonly [K in keyof T]: T[K] }; // remove readonly
type Concrete<T> = { [K in keyof T]-?: T[K] }; // remove optional
type Nullable<T> = { [K in keyof T]: T[K] | null };
// Key remapping with `as` (4.1)
type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] };
// Getters<{ name: string }> = { getName: () => string }
// Filter keys: map unwanted ones to never
type OnlyStrings<T> = { [K in keyof T as T[K] extends string ? K : never]: T[K] };
// Map over a union of strings
type Flags<K extends string> = { [P in K]: boolean };
type FeatureFlags = Flags<'darkMode' | 'beta'>; // { darkMode: boolean; beta: boolean }
// Recursive
type DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K] };
Conditional Types and infer
A extends B ? X : Y chooses a type based on assignability. infer captures part of a type.
type IsString<T> = T extends string ? true : false;
type ElementType<T> = T extends readonly (infer U)[] ? U : never;
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
type FirstArg<F> = F extends (first: infer A, ...rest: never[]) => unknown ? A : never;
type PropType<T, K extends string> = K extends keyof T ? T[K] : never;
// infer with a constraint (4.7)
type FirstString<T> = T extends [infer S extends string, ...unknown[]] ? S : never;
Distribution. When the checked type is a naked type parameter and you pass a union, the conditional runs once per member:
type ToArray<T> = T extends unknown ? T[] : never;
type A = ToArray<string | number>; // string[] | number[]
type ToArrayOnce<T> = [T] extends [unknown] ? T[] : never; // wrap to stop distribution
type B = ToArrayOnce<string | number>; // (string | number)[]
never is an empty union, so a distributive conditional on never gives never.
Template Literal Types
type Greeting = `hello ${string}`; // any string starting with 'hello '
type Size = 'sm' | 'md' | 'lg';
type Variant = 'primary' | 'ghost';
type ButtonClass = `btn-${Variant}-${Size}`; // 6 combinations
type EventName<T extends string> = `on${Capitalize<T>}`;
type Handlers = { [E in 'click' | 'focus' as EventName<E>]: () => void };
// { onClick: () => void; onFocus: () => void }
// Parsing strings with infer
type RouteParams<S extends string> =
S extends `${string}:${infer P}/${infer Rest}` ? P | RouteParams<`/${Rest}`>
: S extends `${string}:${infer P}` ? P
: never;
type P = RouteParams<'/users/:userId/posts/:postId'>; // 'userId' | 'postId'
Keep these readable. Type-level string parsing is powerful but slows the compiler and confuses teammates when overused.
as const, satisfies and Enums
as const
const config = { env: 'prod', ports: [80, 443] } as const;
// { readonly env: 'prod'; readonly ports: readonly [80, 443] }
satisfies (4.9)
Checks that a value matches a type without widening the value’s own type:
type Theme = Record<'primary' | 'secondary', string | [number, number, number]>;
const theme = {
primary: '#3366ff',
secondary: [255, 0, 0],
} satisfies Theme;
theme.primary.toUpperCase(); // ok: still known to be a string
theme.secondary[0]; // ok: still known to be a tuple
const bad = { primary: '#fff' } satisfies Theme; // error: 'secondary' is missing
Use const x: T = ... when you want the variable’s type to be T; use satisfies T when you want validation plus the precise inferred type. as const satisfies T combines both.
Enums and alternatives
enum Direction { Up, Down } // numeric enum: emits a runtime object
enum Status { Active = 'active', Banned = 'banned' } // string enum
Enums generate JavaScript, so they do not work with type-stripping runtimes (Node.js .ts support, erasableSyntaxOnly). The erasable alternative:
export const Status = { Active: 'active', Banned: 'banned' } as const;
export type Status = (typeof Status)[keyof typeof Status]; // 'active' | 'banned'
function setStatus(s: Status) {}
setStatus(Status.Active); // ok
setStatus('banned'); // ok
Or just a union type: type Status = 'active' | 'banned'.
Classes
class Animal {
name: string; // public by default
protected sound = '...'; // visible in subclasses
private secret = 1; // TypeScript-only privacy (erased at run time)
#reallyPrivate = 2; // JavaScript private field (enforced at run time)
static count = 0;
readonly born = new Date();
constructor(name: string) {
this.name = name;
Animal.count++;
}
speak(): string { return `${this.name} says ${this.sound}`; }
}
class Dog extends Animal {
protected override sound = 'woof'; // `override` required with noImplicitOverride
}
abstract class Shape {
abstract area(): number; // subclasses must implement
describe() { return `Area: ${this.area()}`; }
}
interface Serializable { toJSON(): string }
class Point implements Serializable {
x = 0;
y = 0;
toJSON() { return JSON.stringify({ x: this.x, y: this.y }); }
}
// Parameter properties: shorthand that declares and assigns
class Service {
constructor(private readonly db: Database, public name = 'svc') {}
}
// Note: parameter properties are not erasable syntax (no Node type stripping).
// Accessors
class Temperature {
#c = 0;
get fahrenheit() { return this.#c * 9 / 5 + 32; }
set fahrenheit(f: number) { this.#c = (f - 32) * 5 / 9; }
}
// `this` types for fluent APIs
class Builder {
parts: string[] = [];
add(p: string): this { this.parts.push(p); return this; }
}
Explicit resource management (TS 5.2; runtime support in Node.js 24+ and current browsers):
class TempFile implements Disposable {
[Symbol.dispose]() { /* delete the file */ }
}
{
using f = new TempFile();
} // f[Symbol.dispose]() runs here, even on exceptions
// `await using` works with [Symbol.asyncDispose]
Standard decorators (TS 5.0, the TC39 version; no experimentalDecorators flag needed):
function logged<This, Args extends unknown[], R>(
target: (this: This, ...args: Args) => R,
context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => R>,
) {
return function (this: This, ...args: Args): R {
console.log(`call ${String(context.name)}`);
return target.call(this, ...args);
};
}
class Calc {
@logged add(a: number, b: number) { return a + b; }
}
Modules and Imports
// Named and default exports
export const PI = 3.14;
export function area(r: number) { return PI * r * r; }
export default class Circle {}
// Type-only imports and exports: erased completely from output
import type { User } from './types.ts';
import { type Order, createOrder } from './orders.ts';
export type { User };
// Re-exports
export * from './math.ts';
export * as math from './math.ts';
// Import attributes (JSON modules)
import data from './data.json' with { type: 'json' };
// Dynamic import
const { heavy } = await import('./heavy.ts');
verbatimModuleSyntax: true (recommended) makes the rule simple: anything imported without type stays in the output, anything with type is removed. It forces you to mark type-only imports, which is exactly what type-stripping tools need.
File extensions in imports:
| Setup | Write imports as |
|---|---|
Node.js with "module": "nodenext", compiled by tsc |
./file.js (the output name) |
Node.js running .ts directly (type stripping) |
./file.ts + allowImportingTsExtensions (or rewriteRelativeImportExtensions if you also emit) |
Bundler (Vite, esbuild, webpack) with "moduleResolution": "bundler" |
./file (extension optional) |
Declaration Files and Ambient Types
.d.ts files describe types for JavaScript code that has no types of its own.
// types/legacy-lib.d.ts: type an untyped package
declare module 'legacy-lib' {
export function doThing(input: string): number;
const version: string;
export default version;
}
// Wildcard module for asset imports
declare module '*.svg' {
const url: string;
export default url;
}
// Add to globals (file must be a module, hence the export)
declare global {
interface Window { analytics?: { track(event: string): void } }
var __APP_VERSION__: string;
}
export {};
// Augment a library's types (module augmentation)
import 'express';
declare module 'express' {
interface Request { userId?: string }
}
Where types come from:
- Packages that ship their own (
"types"in their package.json). - DefinitelyTyped:
npm install -D @types/node. Since TypeScript 6.0,"types"defaults to[], so list global type packages explicitly:"types": ["node"](or["*"]for the old include-everything behaviour). - Your own
.d.tsfiles insideinclude.
Patterns: Branded Types, Result, Exhaustive Switch
Branded (nominal) types
TypeScript is structural: two number aliases are interchangeable. A brand makes them distinct:
type UserId = number & { readonly __brand: 'UserId' };
type OrderId = number & { readonly __brand: 'OrderId' };
const UserId = (n: number) => n as UserId;
function loadUser(id: UserId) {}
loadUser(42); // error
loadUser(UserId(42)); // ok
const o = 7 as OrderId;
loadUser(o); // error: OrderId is not UserId
Result type instead of exceptions
type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };
function parseAge(input: string): Result<number, string> {
const n = Number(input);
return Number.isInteger(n) && n >= 0 ? { ok: true, value: n } : { ok: false, error: 'Invalid age' };
}
const r = parseAge('42');
if (r.ok) r.value; // number
else r.error; // string
Typed event emitter
type Events = { login: { userId: string }; logout: undefined };
class Bus<E extends Record<string, unknown>> {
on<K extends keyof E>(event: K, fn: (payload: E[K]) => void) { /* ... */ }
emit<K extends keyof E>(event: K, payload: E[K]) { /* ... */ }
}
const bus = new Bus<Events>();
bus.emit('login', { userId: '1' }); // ok
bus.emit('login', {}); // error: userId missing
Full version: examples/generics.ts.
Validate at the edges
Types disappear at run time. Data from JSON.parse, fetch, forms, env vars and databases is unknown until validated. Use a schema library that infers types (Zod, Valibot, ArkType, TypeBox) or hand-written type guards, and avoid as SomeType on external data.
import { z } from 'zod';
const UserSchema = z.object({ id: z.number(), name: z.string() });
type User = z.infer<typeof UserSchema>;
const user = UserSchema.parse(await res.json()); // throws if the shape is wrong
tsconfig.json Cheat Sheet
Node.js app or library (ESM, compiled with tsc)
{
"compilerOptions": {
"target": "es2024",
"module": "nodenext", // also sets moduleResolution: nodenext
"outDir": "dist",
"rootDir": "src",
"types": ["node"],
"strict": true,
"noUncheckedIndexedAccess": true,
"verbatimModuleSyntax": true,
"declaration": true, // emit .d.ts (libraries)
"sourceMap": true,
"skipLibCheck": true
},
"include": ["src"]
}
Node.js running .ts directly (type stripping, no build)
{
"compilerOptions": {
"target": "esnext",
"module": "nodenext",
"types": ["node"],
"strict": true,
"noEmit": true, // tsc only type-checks
"allowImportingTsExtensions": true,
"erasableSyntaxOnly": true, // error on enums, namespaces, parameter properties
"verbatimModuleSyntax": true,
"skipLibCheck": true
}
}
This repo uses this setup: see tsconfig.json.
Front-end app with a bundler (Vite, etc.)
{
"compilerOptions": {
"target": "es2022",
"module": "preserve", // implies moduleResolution: bundler
"lib": ["es2024", "dom"],
"jsx": "react-jsx",
"strict": true,
"noEmit": true, // the bundler emits JS
"isolatedModules": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true
},
"include": ["src"]
}
Option reference
| Option | What it does | Recommendation |
|---|---|---|
strict |
Enables the whole strict family (strictNullChecks, noImplicitAny, strictFunctionTypes, …) |
On (default since 6.0) |
noUncheckedIndexedAccess |
arr[i] and obj[key] include undefined |
On for new code |
exactOptionalPropertyTypes |
prop?: T does not accept explicit undefined |
On if you can |
noImplicitOverride |
Requires override keyword |
On |
noFallthroughCasesInSwitch |
Errors on fallthrough | On |
noUnusedLocals / noUnusedParameters |
Flags dead code | On, or leave it to a linter |
target |
JS version of emitted syntax | Match your oldest runtime |
lib |
Built-in API types available (dom, es2024, …) |
Match your runtime |
module |
Module system of output and resolution rules | nodenext for Node, preserve for bundlers |
moduleResolution |
How imports are found | nodenext or bundler (node/node10 removed in 7.0) |
paths |
Import aliases (@/* to src/*) |
Prefer package.json "imports" (#/*) when possible |
types |
Global type packages to include | List them; defaults to [] since 6.0 |
verbatimModuleSyntax |
Keep/erase imports exactly as written | On |
isolatedModules |
Each file can be transpiled alone | On with any non-tsc transpiler |
erasableSyntaxOnly |
Ban TS-only runtime syntax | On for type stripping |
skipLibCheck |
Skip type-checking .d.ts files |
On (faster) |
declaration / declarationMap |
Emit .d.ts (+ maps) |
Libraries |
composite + references |
Project references for monorepos | Large repos |
incremental |
Cache build info for faster rebuilds | On for big projects |
resolveJsonModule |
Import .json files |
As needed |
allowJs / checkJs |
Include and type-check .js files |
Migrations |
Path aliases with package.json "imports" (supported by Node itself, and #/ prefixes are supported since TS 6.0):
{ "imports": { "#/*": "./src/*" } }
import { db } from '#/db.ts';
TypeScript 6.0 and 7.0: What Changed
TypeScript 6.0 (March 2026) was the last release of the JavaScript-based compiler and a bridge to 7.0. TypeScript 7.0 (July 2026) is the compiler and language service ported to Go: same language, much faster builds (the TypeScript team reports roughly 8x to 12x on full builds). The npm package is still typescript and the command is still tsc.
New defaults (6.0, kept in 7.0):
| Option | New default |
|---|---|
strict |
true |
module |
esnext |
target |
latest stable ES version |
types |
[] (add "types": ["node"] etc.) |
rootDir |
the folder containing tsconfig.json |
noUncheckedSideEffectImports |
true |
Deprecated in 6.0 and removed in 7.0 (errors):
target: "es5"anddownlevelIterationmoduleResolution: "node"/"node10"/"classic"(usenodenextorbundler)module: "amd" | "umd" | "system" | "none"outFile(use a bundler)baseUrl(makepathsrelative to the project, or use package.jsonimports)- Setting
esModuleInterop,allowSyntheticDefaultImportsoralwaysStricttofalse module Foo {}namespace syntax (usenamespace Foo {})- Import
assert { type: 'json' }(usewith { type: 'json' }) - Passing file names to
tscwhile atsconfig.jsonexists (use--ignoreConfig)
Migration checklist:
- Upgrade to 6.0 first and fix every deprecation warning (temporarily silence with
"ignoreDeprecations": "6.0"). - Add
"types": [...]explicitly. - Replace
baseUrl-based imports. - Move to 7.0. Tools that use the TypeScript compiler API (some linters, framework plugins) may still need 6.0 until 7.x ships a new API; the
@typescript/typescript6package lets both versions coexist.
Running TypeScript
| Tool | Type-checks? | Notes |
|---|---|---|
tsc |
Yes | The reference compiler. tsc --noEmit to only check. tsc -w to watch. |
Node.js (node file.ts) |
No | Strips types; erasable syntax only; imports need .ts extensions |
| Deno, Bun | No (Deno has deno check) |
Run .ts natively |
tsx |
No | Runs .ts with esbuild, supports enums and paths |
| esbuild, SWC, Vite | No | Fast transpilers for builds and dev servers |
Typical scripts:
{
"scripts": {
"dev": "node --watch src/main.ts",
"typecheck": "tsc --noEmit",
"build": "tsc",
"test": "node --test"
}
}
Always run tsc --noEmit in CI, because every fast runner skips type checking.
Common Errors and Fixes
| Error | Typical cause | Fix |
|---|---|---|
TS2322 Type 'X' is not assignable to type 'Y' |
Value does not match annotation | Fix the value, or widen/narrow the type |
TS2339 Property 'x' does not exist on type 'Y' |
Accessing a member not on every union member, or a typo | Narrow first; check the type |
TS2345 Argument of type 'X' is not assignable to parameter of type 'Y' |
Wrong argument | Check overloads and generics |
TS18047 / TS18048 'x' is possibly 'null' / 'undefined' |
strictNullChecks |
Narrow with if, ?., ??; use ! only when you are sure |
TS7006 Parameter 'x' implicitly has an 'any' type |
noImplicitAny |
Annotate the parameter |
TS2307 Cannot find module 'x' |
Missing package/types, wrong path or extension | Install @types/x, fix moduleResolution, add extension |
TS2304 Cannot find name 'process' |
Node types not loaded | npm i -D @types/node and "types": ["node"] |
TS2531 Object is possibly 'null' |
DOM APIs like getElementById |
Check for null or assert |
TS2366 Function lacks ending return statement |
Not all paths return | Add the missing return or never check |
TS2564 Property has no initializer |
strictPropertyInitialization |
Initialize, assign in constructor, or !: if set elsewhere |
TS2589 Type instantiation is excessively deep |
Recursive types too deep | Simplify, add depth limits |
TS1484 'X' is a type and must be imported using a type-only import |
verbatimModuleSyntax |
import type { X } |
TS1294 This syntax is not allowed when 'erasableSyntaxOnly' is enabled |
enum, namespace, parameter property | Use as const objects, modules, explicit fields |
TS2352 Conversion of type 'X' to type 'Y' may be a mistake |
Unsafe as cast |
Validate instead; as unknown as Y only as a last resort |
Escape hatches, in order of preference: narrowing > satisfies > type predicate > as > // @ts-expect-error (fails if the error goes away) > // @ts-ignore > any.
Feature Version Table
| Feature | Version |
|---|---|
| Template literal types, key remapping in mapped types | 4.1 |
satisfies operator |
4.9 |
accessor keyword, in narrowing for unlisted properties |
4.9 |
Standard decorators, const type parameters |
5.0 |
using declarations |
5.2 |
NoInfer |
5.4 |
| Inferred type predicates | 5.5 |
--rewriteRelativeImportExtensions |
5.7 |
--erasableSyntaxOnly |
5.8 |
New defaults (strict, types: []), es2025 target, #/ imports |
6.0 |
| Native (Go) compiler, deprecated options removed | 7.0 |
Resources
- TypeScript Handbook: the official guide.
- TSConfig Reference: every compiler option explained.
- TypeScript Playground: try snippets and see the emitted JS.
- TypeScript blog: release announcements, including 6.0 and 7.0.
- Node.js TypeScript docs: what type stripping supports.
- DefinitelyTyped: community type definitions (
@types/*). - type-challenges: practice type-level programming.
- Total TypeScript: tutorials and articles by Matt Pocock.
Runtime Validation Libraries Compared
Types disappear at run time, so external data needs a validator that also produces types.
| Library | Style | Strength |
|---|---|---|
| Zod | Chainable schemas, z.infer |
Most popular, huge ecosystem (forms, tRPC, OpenAPI) |
| Valibot | Small composable functions | Tiny bundles for front ends |
| ArkType | Type-syntax strings | Very fast, TypeScript-like definitions |
| TypeBox | JSON Schema builder | Standard JSON Schema output, fast validation |
Many of these implement Standard Schema, so frameworks can accept any of them.
FAQ
type or interface?
Either for object shapes. Use interface for public object types that may be extended, type for unions, tuples and computed types. Consistency matters more than the choice.
Should I use enum?
Prefer as const objects or union types. Enums emit JavaScript and do not work with type-stripping runtimes.
What is the difference between any and unknown?
any turns checking off; unknown forces you to narrow before use. Use unknown for untrusted data.
Do I need strict: true?
Yes, and it is the default since TypeScript 6.0. Add noUncheckedIndexedAccess too.
Is TypeScript 7 a different language? No. It is the same language with a compiler rewritten in Go. Code that compiles on 6.0 without deprecated options generally compiles the same on 7.0.
How do I type-check in CI if I run .ts files directly?
Run tsc --noEmit as a separate step; Node, Bun, tsx and bundlers only strip types.
Why does JSON.parse return any?
For historical reasons. Annotate the result as unknown and validate it.
Where to Go Next
- Read the TypeScript Handbook chapters on narrowing and generics.
- Turn on
strict,noUncheckedIndexedAccessandverbatimModuleSyntaxin a real project and fix the errors. - Solve a few easy and medium type-challenges to get fluent with conditional and mapped types.
- Add a runtime validator at every boundary (HTTP, env vars, JSON files).
- Try the TypeScript 7 compiler on your project and compare build times.
Contributing
PRs welcome. Keep entries accurate and version-aware (say which TypeScript version introduced a feature). New examples go in examples/ with compile-time Expect<Equal<...>> checks or runtime tests in test/, and npm run check must pass.
License
MIT. See LICENSE.
If this helped you, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.