DEVELOPER SANDBOX Academy of Mastery
WelcomeBuild · Explore · Create SD
REFERENCE GUIDE

TypeScript Reference Guide

TypeScript syntax, compiler, configuration, tooling, modules, generics, and macOS development reference.

Quick jump:

TypeScript at a Glance

TypeScript is JavaScript plus static type checking. Types improve editor tooling and catch errors before runtime, then are normally erased from emitted JavaScript.

Current baseline: TypeScript 7.0.2.

What TypeScript Adds

Type annotations, inference, unions, interfaces, generics, narrowing, declaration files, mapped types, conditional types, and editor intelligence.

Not a Runtime

TypeScript does not replace JavaScript. Browsers and Node execute JavaScript. TypeScript checks and transforms source before or alongside runtime tooling.

Core Files

.ts = TypeScript · .tsx = TypeScript + JSX · .d.ts = declarations · tsconfig.json = project configuration.

Preferred Install

npm install -D typescript

Keep TypeScript project-local so each repository controls its compiler version.

Inference

Do not annotate everything. const count = 3 already gives TypeScript useful type information.

Types Disappear

Interfaces, generic parameters, and most type annotations do not exist at runtime. Use real runtime validation for API and user data.

Modules Matter

Compiler module settings must match Node, a browser framework, or the bundler that actually executes the JavaScript.

TypeScript 7

TypeScript 7 uses the new native compiler/tooling foundation and keeps the familiar TypeScript language model while substantially improving compiler performance.

macOS Setup & Installation

Use Node and npm on macOS. Prefer a local TypeScript installation for real projects.

Purpose / Commands / Notes

Verify Node

Node and npm provide the normal TypeScript installation workflow.

node -v
npm -v
which node
which npm

If you use nvm, activate the project Node version before installing dependencies.

Install Locally

Recommended for projects.

npm install -D typescript
npx tsc --version

The compiler version is captured by package metadata and the lockfile.

Optional Global

Useful for quick experiments, but not the project baseline.

npm install -g typescript
tsc --version

Real repositories should still run their local TypeScript version.

Playground

No installation required.

Useful for syntax experiments, narrowing, compiler output, and type inference.

Create a TypeScript Project

Minimal project workflow for macOS and Node-based development.

Initialize

Create a project and install TypeScript.

mkdir ts-demo
cd ts-demo
npm init -y
npm install -D typescript
npx tsc --init
Create Source Folder

Separate authored TypeScript from generated output.

mkdir src
touch src/index.ts
First TypeScript

Explicit annotation plus inference.

const project: string = "Sandbox";
const count = 3;

console.log(project, count);
Type Check

Check types without producing JavaScript.

npx tsc --noEmit
Compile

Compile according to tsconfig.

npx tsc
node dist/index.js
Watch

Recompile when files change.

npx tsc --watch

Compiler Command Reference

tsc is the TypeScript compiler. Prefer npx tsc so the project-local compiler is used.

Version
Initialize
Compile Project
Type Check Only
Watch
Specific Project
Show Effective Config
List Files
Explain Files
Trace Module Resolution
All Compiler Options
Project References

tsconfig.json Quick Reference

tsconfig.json marks the project root and controls files, checking, module behavior, and JavaScript/declaration output.

Modern Node ESM

Practical Node configuration. Install @types/node.

Modern Bundler

Useful when Vite or another bundler handles JavaScript output.

strict

Turns on the strict checking family.

target

Controls the JavaScript syntax/runtime level TypeScript emits or assumes.

module / moduleResolution

Match these settings to the actual runtime or bundler.

rootDir / outDir

Control source-tree structure and emitted output location.

types

List global type environments your project needs.

sourceMap

Generate source maps so debuggers can map JavaScript back to TypeScript.

declaration

Emit .d.ts files describing your public API.

noUncheckedIndexedAccess

Add undefined to uncertain indexed reads.

exactOptionalPropertyTypes

Distinguish missing optional properties from explicitly supplied undefined values.

Everyday Types & Syntax

Use annotations where they communicate intent. Let TypeScript infer obvious local values.

string
let title: string = "Sandbox";
number
let total: number = 42;
boolean
let active: boolean = true;
Array
const names: string[] = ["A", "B"];

const ids: Array<number> = [1, 2];
Tuple
const point: [number, number] = [10, 20];
Literal Union
type Status =
  | "draft"
  | "active"
  | "archived";
null / undefined
let result: string | null = null;

let value: string | undefined;
unknown
let payload: unknown;

Narrow it before using it.

any
let legacy: any;

Turns off most useful checking. Keep its use limited.

never
function fail(message: string): never {
  throw new Error(message);
}
void
function log(message: string): void {
  console.log(message);
}
readonly
const ids: readonly number[] = [1, 2, 3];

Objects, Interfaces & Type Aliases

Both interface and type can describe object shapes. Type aliases can also represent unions and other non-object types.

Concept / Syntax / Guidance

interface

Named object contract.

interface User {
  id: number;
  name: string;
  active?: boolean;
}

Interfaces can extend other interfaces and participate in declaration merging.

type alias

Name an object, primitive union, tuple, mapped type, or other type expression.

type UserId = string | number;

type Point = {
  x: number;
  y: number;
};

Especially useful for unions, intersections, and constructed types.

Optional Property

The property may be absent.

interface User {
  nickname?: string;
}

Optional does not mean every consumer can safely assume a value exists.

readonly Property

Prevent assignment through that typed reference.

interface User {
  readonly id: number;
}

This is compile-time protection, not automatic Object.freeze runtime behavior.

Index Signature

Unknown property names with a consistent value type.

interface Scores {
  [name: string]: number;
}

Useful for dictionary-like objects.

Intersection

Require multiple contracts at once.

type Timestamped = {
  createdAt: Date;
};

type SavedUser =
  User & Timestamped;

Good for clear composition; avoid unreadably deep intersections.

satisfies

Check a value against a type while preserving useful inference.

const routes = {
  home: "/",
  users: "/users"
} satisfies Record<string, string>;

Often preferable to a broad type assertion for configuration objects.

Functions

Type function boundaries where the contract matters. Let obvious implementation details infer naturally.

Parameters + Return
Optional Parameter
Default Parameter
Rest Parameters
Function Type
Generic Function
Generic Constraint

Unions & Narrowing

A union means a value can have several possible types. Narrowing proves which member is present before member-specific operations are used.

Union
typeof
Array.isArray
in Operator
instanceof
Discriminated Union
Type Predicate

Generics

Generics let reusable code preserve relationships between types instead of collapsing everything into a broad base type.

Identity
Array Element
Multiple Parameters
keyof Constraint
Generic Interface

Type Operators & Type Construction

Build new types from existing types and values.

keyof
type UserKey =
  keyof User;
typeof
const config = {
  port: 3000
};

type Config =
  typeof config;
Indexed Access
type UserName =
  User["name"];
as const
const roles =
  ["admin", "user"] as const;

type Role =
  typeof roles[number];
Mapped Type
type Flags<T> = {
  [K in keyof T]: boolean;
};
Conditional Type
type Element<T> =
  T extends readonly (infer U)[]
    ? U
    : T;
Template Literal Type
type EventName =
  `user:${"created" | "deleted"}`;

Classes & OOP Syntax

TypeScript classes are JavaScript classes plus compile-time type features.

Basic Class
Access Modifiers
readonly
implements
abstract

Modules, Imports & Exports

Compiler module settings must agree with how Node or your bundler really loads JavaScript.

Named Export / Import
Default Export
Type-only Import
Mixed Import
Dynamic Import

Async, Promises & Fetch

TypeScript adds types to JavaScript asynchronous behavior; Promise mechanics remain JavaScript runtime behavior.

Promise Return Type
await
Promise.all
External JSON
Error Narrowing

DOM & Browser TypeScript

DOM declarations provide strongly typed elements, browser events, fetch, URL, storage, and related APIs.

querySelector

Specify the expected element shape.

const input =
  document.querySelector<HTMLInputElement>(
    "#name"
  );

if (input) {
  console.log(input.value);
}
Events

Narrow element-specific event values.

input?.addEventListener(
  "input",
  event => {
    const target =
      event.currentTarget
      as HTMLInputElement;

    console.log(target.value);
  }
);
Forms

Typed browser form element.

const form =
  document.querySelector<HTMLFormElement>(
    "#profile"
  );

form?.addEventListener(
  "submit",
  event => {
    event.preventDefault();
  }
);
localStorage

Stored values are strings and may be absent.

const theme =
  localStorage.getItem("theme");

// string | null

TypeScript with Node.js

Add Node declaration packages for globals and built-in modules. Runtime execution and static checking are separate concerns.

Install Node Types
Node Global Types
Built-in Module
process
Modern Node Direct Execution
tsx Runner

Declaration Files & Third-Party Types

.d.ts files describe types without providing runtime implementation.

@types Packages
Bundled Types
Module Declaration
Emit Declarations
Declaration-only Build

Built-in Utility Types

Transform existing types instead of duplicating related object definitions.

Partial<T>
type UserPatch =
  Partial<User>;

All properties optional.

Required<T>
type CompleteUser =
  Required<User>;
Readonly<T>
type LockedUser =
  Readonly<User>;
Pick<T,K>
type UserSummary =
  Pick<User, "id" | "name">;
Omit<T,K>
type NewUser =
  Omit<User, "id">;
Record<K,V>
type UserMap =
  Record<string, User>;
NonNullable<T>
type Name =
  NonNullable<
    string | null | undefined
  >;
ReturnType<F>
type Result =
  ReturnType<
    typeof createUser
  >;
Parameters<F>
type Args =
  Parameters<
    typeof createUser
  >;
Awaited<T>
type Data =
  Awaited<
    Promise<User[]>
  >;

Modern Tooling & Build Integration

Many modern frameworks and bundlers transform TypeScript source separately while tsc provides static type checking.

Project-local Compiler
Vite
tsx
ESLint
Prettier
Project References
Nightly Compiler

Best Implementation Practices

TypeScript is most useful when it makes boundaries, state, and relationships clearer instead of adding annotations everywhere.

Install Locally
Keep Strict Checking
Prefer Local Inference
Model States with Unions
Prefer unknown to any
Assertions Are Not Validation
Use import type
Match the Runtime

Troubleshooting Fast Map

Check compiler version, effective configuration, included files, and module resolution before changing types blindly.

tsc Not Found

Install locally:

npm install -D typescript
npx tsc --version
Wrong Version

Compare npx tsc --version with tsc --version. Use the local version for project work.

tsconfig Seems Ignored

Passing source files directly to tsc can bypass project configuration. Run npx tsc or use -p.

Unexpected File Included

Use npx tsc --explainFiles or --listFilesOnly.

Cannot Find Module

Run npx tsc --traceResolution. Check file extensions, package exports, and module resolution mode.

Cannot Find process

Install @types/node and add "types": ["node"] to Node projects.

Possibly undefined

Check, narrow, default, or redesign the value. Do not automatically silence the warning with !.

Property Missing on Union

Narrow with a discriminant, typeof, in, instanceof, or a custom type guard.

Wrong Output Folder

Inspect rootDir, outDir, and npx tsc --showConfig.

Editor Differs from CLI

Make sure your editor is using the workspace TypeScript version rather than an older bundled compiler.

Official Documentation & Downloads

Use official TypeScript documentation for syntax, compiler configuration, modules, declarations, and version-specific changes.

TypeScript Home

Main TypeScript website.

Download / Install

Official installation instructions.

Documentation Home

Handbook, reference material, declarations, configuration, and cheat sheets.

Handbook

Primary guide to TypeScript concepts.

Everyday Types

Common types and basic syntax.

Narrowing

Control-flow analysis and type guards.

Functions

Function typing and signatures.

Object Types

Interfaces, properties, tuples, intersections, and related structures.

Generics

Generic functions, constraints, interfaces, and classes.

Creating Types from Types

keyof, typeof, indexed, conditional, mapped, and template literal types.

Classes

TypeScript class syntax.

Modules

Module syntax and behavior.

Modules Reference

Detailed module formats and resolution behavior.

Utility Types

Built-in type transformations.

tsconfig.json

How project configuration works.

TSConfig Reference

Compiler option reference.

tsc CLI

Compiler command reference.

Declaration Files

Authoring and consuming .d.ts files.

DOM Manipulation

TypeScript with browser DOM APIs.

Migrating from JavaScript

Gradual JavaScript-to-TypeScript adoption.

Playground

Run examples and inspect compiler inference/output in the browser.

TypeScript 7

Native TypeScript 7 compiler architecture and migration information.

npm Package

Current package and release versions.