Bookmarks
ReferenceFrontendBackendVerified

TypeScript

TypeScript is a statically typed language built on JavaScript that checks code before it runs. The reference covers types, generics, modules, tsconfig and tsc errors.

checked 1 Nov · next check 8 Nov · 56 min read

Sections
13
Reading
56 min
Current version
7.0.2
Written from
typescriptlang.org/docs

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What TypeScript is and how it works

TypeScript is a programming language that adds static typing to JavaScript: the types of values are checked before the program runs. The tsc compiler finds errors and emits plain JavaScript with the types removed.

TypeScript pays off where code grows and several people edit it. The check catches misspelt property names, wrong arguments and a forgotten null, and the editor uses the same types to suggest methods and find every usage. Any working JavaScript is also valid TypeScript syntax, so a project can be migrated one file at a time. TypeScript does not check data at run time and does not change how the code behaves: an API response or user input still has to be validated in code.

The compiler does two independent jobs. It checks types and prints errors, then erases the annotations (type erasure) and emits .js. By default, type errors do not stop the files from being emitted, so code being migrated to TypeScript keeps working. Node.js and bundlers can only erase types, so in projects where they run the code, run the check separately: npx tsc --noEmit.

To make errors stop app.js from being emitted, enable the noEmitOnError option.

What remains after compilation

Annotations are written after the name, following a colon. They are absent from tsc output: the interface disappears entirely, while the function code stays the same.

typescriptsrc/index.ts
interface User {  name: string;  id: number;} export function greet(user: User): string {  return `Salom, ${user.name}!`;} console.log(greet({ name: "Aziza", id: 1 }));
javascriptdist/index.js after tsc
export function greet(user) {    return `Salom, ${user.name}!`;}console.log(greet({ name: "Aziza", id: 1 }));

Structural typing

Type compatibility is determined by the shape of a value (structural typing), not by the name of its type. An object fits wherever a Point is expected if it has x and y fields of the right types; extra fields do no harm. The exception is an object literal written directly in place of the value: an extra field there is treated as a typo.

typescriptpoint.ts
interface Point {  x: number;  y: number;} function show(p: Point): string {  return `${p.x}, ${p.y}`;} const marker = { x: 12, y: 26, label: "A" };console.log(show(marker)); // error TS2353: property label does not exist in type Point// const corner: Point = { x: 0, y: 0, label: "B" };
textexample output
12, 26

How tsc differs from Node.js and transpilers

FeaturetscNode.jsBabel, swc, Sucrase
Checks typesyesnono
What it does with .tsemits .jsreplaces types with spaces and runs the file immediatelyemits .js
Limitationsnoneerasable syntax only: no enum or namespace with codefiles are processed one at a time: enable the isolatedModules option in tsc

Which tool to use: tsc is always the one that checks types, while Node.js and transpilers can run or build the code. They are faster because they do not check. If something other than tsc emits the .js in your project, add npx tsc --noEmit to CI, otherwise nobody will see type errors.

What you need to know first

  • The JavaScript language: functions, objects, classes, modules and promises — see the JavaScript reference. TypeScript does not change how they behave; it only describes their types.
  • Node.js and npm: installation, package.json, running scripts — see the Node.js reference.
  • The command line: directories, running commands, environment variables — see the Bash reference.

Section sources

the section is written from these pages

Cheat sheet

Everyday type syntax, utility types and tsc commands. Each line is explained in detail in its own section: basic types, narrowing, generics, operations on types and tsconfig.json.

Types

TaskSyntax
Variable annotationlet title: string = "Hisobot";
Arrayconst ids: number[] = [1, 2];
Tupleconst pair: [string, number] = ["yosh", 30];
One of several typeslet id: string | number;
Only specific valuestype Method = "GET" | "POST";
Optional and read-only properties{ readonly id: number; note?: string }
Dictionaryconst stock: Record<string, number> = {};
Function typetype Handler = (event: string) => void;
Value of unknown typelet input: unknown;
Literal types instead of string and numberconst roles = ["admin", "user"] as const;
Check an object without widening its typeconst cfg = { port: 8080 } satisfies Config;

Narrowing and generics

TaskSyntax
Check a primitiveif (typeof x === "string")
Check that a property existsif ("swim" in animal)
Check a classif (err instanceof Error)
Custom type guardfunction isUser(x: unknown): x is User
Exhaustiveness check in switchdefault: { const rest: never = shape; }
Generic functionfunction first<T>(items: T[]): T | undefined
Constraint on a type parameter<T extends { length: number }>
Keys of a typetype Key = keyof User;
Type of a propertytype Id = User["id"];
Type of a variabletype Config = typeof config;

Utility types

TypeResult
Partial<User>all properties optional
Required<User>all properties required
Readonly<User>all properties read-only
Pick<User, "id" | "name">only the listed properties
Omit<User, "password">all properties except the listed ones
Record<"ru" | "uz", string>an object with exactly these keys
ReturnType<typeof load>the function’s return type
Parameters<typeof load>a tuple of the parameter types
Awaited<Promise<User>>the type after await: User
NonNullable<string | null>without null and undefined: string
Exclude<"a" | "b", "a">the union without the given members: "b"

Commands

TaskCommand
Install in a projectnpm install -D typescript
Compiler versionnpx tsc --version
Create tsconfig.jsonnpx tsc --init
Check types without emitting filesnpx tsc --noEmit
Build the projectnpx tsc
Rebuild on changesnpx tsc --watch
Build a project with project referencesnpx tsc -b
Show the resolved configurationnpx tsc --showConfig
Why a file is part of the projectnpx tsc --explainFiles
How a module was resolvednpx tsc --traceResolution
Run a .ts file in Node.js without type checkingnode src/index.ts

Section sources

the section is written from these pages

Installation and first run

Install TypeScript in every project as an npm dev dependency: that way the project has its own compiler version, the same for every developer and in CI. You need Node.js and npm; verify the result with npx tsc --version.

Installing in a project

The commands are the same on Linux, macOS and Windows. The typescript package contains the tsc compiler, and @types/node provides types for the Node.js API: process, node:fs and others. The -D flag saves the packages to devDependencies.

bashin the terminal
mkdir hello-tscd hello-tsnpm init -ynpm pkg set type=modulenpm install -D typescript @types/nodenpx tsc --init

npx tsc runs the compiler from the project’s node_modules/.bin. The "type": "module" line in package.json makes .ts files count as ES modules: both Node.js and tsc take the format from this field. A global npm install -g typescript is fine for experiments, but in a project keep the compiler local so that builds are reproducible on any machine.

To verify, run npx tsc --version: it prints a Version line with the installed version number, which matches the typescript version in devDependencies. In an editor, TypeScript is provided through a language server and underlines type errors as you type. In MSBuild projects such as ASP.NET Core, TypeScript is added with the Microsoft.TypeScript.MSBuild NuGet package.

What tsc --init creates

npx tsc --init writes a short tsconfig.json with recommended strict settings. The main ones are:

  • "module": "nodenext" and "target": "esnext" — code for modern Node.js
  • "strict": true, noUncheckedIndexedAccess and exactOptionalPropertyTypes — strict checks
  • "types": [] — global types from @types packages are not loaded until you list them
  • verbatimModuleSyntax and isolatedModules — import rules that other tools understand too
  • skipLibCheck — skip checking the .d.ts files of libraries
  • declaration, declarationMap and sourceMap — declaration files and source maps next to the .js

For a Node.js application, uncomment rootDir and outDir and replace "types": [] with "types": ["node"]. This is the file after editing, without comments and without the options for publishing libraries:

jsontsconfig.json
{  "compilerOptions": {    "rootDir": "./src",    "outDir": "./dist",    "module": "nodenext",    "target": "esnext",    "types": ["node"],    "strict": true,    "noUncheckedIndexedAccess": true,    "exactOptionalPropertyTypes": true,    "verbatimModuleSyntax": true,    "isolatedModules": true,    "skipLibCheck": true  },  "include": ["src"]}

Your first project

textproject structure
hello-ts/├── node_modules/├── package.json├── tsconfig.json└── src/    └── index.ts
typescriptsrc/index.ts
const who: string = process.argv[2] ?? "dunyo";console.log(`Salom, ${who}!`);
bashin the terminal
npx tscnode dist/index.js Aziza
textexample output
Salom, Aziza!

With no arguments, npx tsc reads tsconfig.json, checks the files in include and writes .js to outDir. If the code has type errors, it prints them but still emits the files; to make errors stop the build, enable noEmitOnError. Two modes are handy while you work:

bashin the terminal
# type-check only, no files emitted: this is how CI checksnpx tsc --noEmit# rebuild every time a file is savednpx tsc --watch

Running .ts in Node.js without a build step

Node.js runs .ts files itself: it replaces the annotations with spaces and runs the code (type stripping). This is enabled by default since Node.js 22.18.0 and 23.6.0 and is stable since 24.12.0 and 25.2.0. Types are not checked, and Node.js does not read tsconfig.json.

bashin the terminal
node src/index.ts Aziza

Only erasable syntax works: enum, namespace with code, constructor parameter properties and import aliases such as import X = Space.X cause the ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX error. Imports must include the .ts extension, and type-only names are imported with import type. To have tsc check such code under the same rules, the Node.js documentation recommends these settings:

jsontsconfig.json
{  "compilerOptions": {    "noEmit": true,    "target": "esnext",    "module": "nodenext",    "types": ["node"],    "rewriteRelativeImportExtensions": true,    "erasableSyntaxOnly": true,    "verbatimModuleSyntax": true  }}

Section sources

the section is written from these pages

Basic types

A type describes which values a variable can hold and what you can do with them. Most of the time TypeScript infers the type itself; you write it explicitly on function parameters and wherever the inferred type is too wide.

Primitives and arrays

TypeValuesExample
stringstringslet city: string = "Toshkent";
numberany number: there are no separate types for integers and fractionslet price: number = 12.5;
booleantrue and falselet paid: boolean = false;
bigintintegers of any lengthlet big: bigint = 100n;
symbolunique keysconst key: symbol = Symbol("id");
null, undefinedabsence of a valuelet note: string | null = null;
string[], Array<string>an array of strings; both forms are equivalentconst tags: string[] = ["ts"];

String, Number and Boolean with a capital letter are different, special built-in types. In annotations, write string, number and boolean. Tuples such as [string, number] are covered in the section “Objects, interfaces and classes”.

Annotations and type inference

An annotation is written after the name, following a colon: let port: number. Without one, the type is inferred (type inference) from the initial value, from return, and from the place where the expression appears: the callback parameter in filter gets the type of the array element. Where inference gives the same type, you do not need an annotation.

typescriptinfer.ts
// type string: a let can be reassigned another stringlet city = "Toshkent";// type 8080: a const never changes, so the type is the literal itselfconst port = 8080;// type (number | null)[]const scores = [90, 75, null];// the type of s is inferred from the array: number | nullconst passed = scores.filter((s) => s !== null && s >= 80);console.log(city, port, passed);
textexample output
Toshkent 8080 [ 90 ]

Function parameters have nothing to infer from, so without an annotation they get the type any. With the noImplicitAny option this is an error, so always write parameter types, except for callbacks: their type comes from the call site (contextual typing).

Unions and literal types

A union type string | number means “one of”: the value can be of any of these types. You can use only what every member of the union has, so before calling toUpperCase() you narrow the type with a check; see the section “Type narrowing” for details. A literal type is a specific value: the type "GET" | "POST" accepts only those two strings.

typescriptliteral.ts
type Method = "GET" | "POST"; function send(url: string, method: Method): string {  return `${method} ${url}`;} const req = { url: "/api/users", method: "GET" };// error TS2345: req.method has type string, not Method// send(req.url, req.method); const fixed = { url: "/api/users", method: "GET" } as const;console.log(send(fixed.url, fixed.method));
textexample output
GET /api/users

TypeScript treats object properties as mutable, so method: "GET" is inferred as string. The as const suffix makes each property a literal type, as if it were a constant.

any, unknown, never and void

TypeMeaningWhat you can do with the value
anytype checking is turned offanything; no errors will be reported
unknownany value, type not yet knownnothing until the type is narrowed by a check
neverno value can existnothing: it marks the result of a function that always throws and a branch where no options are left
voidthe function returns nothingthe result is not used

unknown is the safe replacement for any for data from outside: the result of JSON.parse(), an API response, a settings file. The compiler will not let you access a field until you check the type.

typescriptunknown.ts
function parseConfig(text: string): unknown {  return JSON.parse(text);} const data = parseConfig('{"port": 8080}');// error TS18046: 'data' is of type 'unknown'// console.log(data.port); if (typeof data === "object" && data !== null && "port" in data) {  console.log(data.port);}
textexample output
8080

null and undefined

With strictNullChecks, null and undefined are not part of other types: a value of type string | undefined has to be checked before you call string methods. The usual JavaScript checks and the ?. and ?? operators work well here.

typescriptnulls.ts
function shortName(first: string, last?: string): string {  if (last === undefined) {    return first;  }  return `${first} ${last.charAt(0)}.`;} const user: { email?: string } = {};console.log(shortName("Aziza"), shortName("Aziza", "Karimova"));console.log(user.email?.toLowerCase() ?? "email not provided");
textexample output
Aziza Aziza K.email not provided

The ! operator after an expression (value!) tells the compiler “this is neither null nor undefined” without checking anything at run time. If that is untrue, the program fails where TypeScript showed no error, so write a check instead of using !.

type and interface

You name an object’s shape with an interface or a type alias, type. Almost everything an interface can do, type can do too. The difference is that an interface can be extended by declaring it again, while type can name any type: a union, a primitive, a function. The documentation recommends using interface until you need features of type; for a detailed comparison, see the section “Objects, interfaces and classes”.

TypeScript checks compatibility by the shape of a value (structural typing), not by the name of its type: extra properties on an object do no harm, but an extra property in a literal written in place of the value is treated as a typo. Excess property checking is covered in the section “Objects, interfaces and classes”.

Checking without losing the type: satisfies

The annotation const x: T replaces the inferred type with T. The satisfies T operator (since TypeScript 4.9) only checks that the value fits T and keeps the inferred type precise.

typescriptsatisfies.ts
type Rgb = [number, number, number];type Color = string | Rgb; const palette = {  red: [255, 0, 0],  green: "#00ff00",} satisfies Record<string, Color>; // green stays string, not string | Rgbconsole.log(palette.green.toUpperCase());// red stays the tuple Rgbconsole.log(palette.red[0]);
textexample output
#00FF00255

With the annotation const palette: Record<string, Color>, palette.green would have the type Color, and the toUpperCase() call would not compile: a tuple has no such method.

enum and unions of literals

enum is one of the few TypeScript constructs that does more than describe types: it also creates an object at run time. In modern code, an object with as const is often enough instead: the code stays plain JavaScript, and the type of the values is derived from the object itself. Why enum prevents running .ts in Node.js without a build step is described in the section “Installation and first run”.

typescriptstatus.ts
const Status = {  Draft: "draft",  Published: "published",} as const; type Status = (typeof Status)[keyof typeof Status]; function publish(current: Status): Status {  return current === Status.Draft ? Status.Published : current;} console.log(publish("draft"), publish(Status.Published));
textexample output
published published

Here the type Status is "draft" | "published": the function accepts both the constant Status.Draft and the string "draft".

Section sources

the section is written from these pages

Narrowing

Narrowing refines a type inside a branch of code: after a typeof id === "string" check, TypeScript knows that id is a string. Ordinary JavaScript constructs narrow types: typeof, instanceof, in, comparisons, assignments and an early return.

The compiler walks every execution path of a function (control flow analysis) and knows the narrowest type of a variable at each point. A branch with return leaves the function, so whatever that branch handled drops out of the union afterwards. Assignment narrows a type too, but the new value must fit the variable’s declared type.

typescriptformat-id.ts
function formatId(id: string | number): string {  if (typeof id === "string") {    // here id: string    return id.toUpperCase();  }  // after the return only number is left  return id.toString().padStart(6, "0");} console.log(formatId("ab12"), formatId(42));
textexample output
AB12 000042

Ways to narrow

CheckExampleType in the branch
typeoftypeof x === "number"number
Truthinessif (name)without null and undefined
Equalityx !== null, x != nullwithout null; != null removes undefined too
in"swim" in animalunion members that have this property
instanceoferr instanceof ErrorError
Assignmentx = 1number until the next assignment
Discriminant propertyshape.kind === "circle"Circle, the union member with that kind
Type guardisUser(value)User

Discriminated unions

If every member of a union has a common field with a literal type, it is a discriminated union. Checking that field narrows the value to a single member. This is how you describe messages, events and request results that have different sets of fields.

typescriptshapes.ts
interface Circle {  kind: "circle";  radius: number;} interface Square {  kind: "square";  side: number;} type Shape = Circle | Square; function area(shape: Shape): number {  switch (shape.kind) {    case "circle":      return Math.PI * shape.radius ** 2;    case "square":      return shape.side ** 2;    default: {      const unhandled: never = shape;      return unhandled;    }  }} console.log(area({ kind: "square", side: 3 }));
textexample output
9

Exhaustiveness checking with never

In the default branch no variants are left, so shape gets the type never (a type with no values). If you add a new Triangle member to Shape and forget its case, the assignment becomes the error Type 'Triangle' is not assignable to type 'never'. and the compiler points to every switch that needs updating.

Custom type guards

A type guard is a function whose return type is a predicate value is Type. If it returns true, the value has that type in the branch, and in the else branch it has the remaining union members. Since TypeScript 5.5 the compiler infers the predicate of simple functions itself: filter((id) => id !== undefined) returns an array without undefined.

typescriptguards.ts
interface User {  id: number;  name: string;} function isUser(value: unknown): value is User {  return (    typeof value === "object" &&    value !== null &&    "id" in value &&    typeof value.id === "number" &&    "name" in value &&    typeof value.name === "string"  );} const input: unknown = JSON.parse('{"id": 7, "name": "Aziza"}');if (isUser(input)) {  console.log(input.name);} const ids = [7, undefined, 9].filter((id) => id !== undefined);console.log(ids.map((id) => id * 2));
textexample output
Aziza[ 14, 18 ]

Assertion functions

An assertion function with the return type asserts value is T or asserts condition returns nothing and throws an exception if the condition is false. After it is called, the type stays narrowed until the end of the scope.

typescriptassert.ts
function assertDefined<T>(  value: T,  name: string,): asserts value is NonNullable<T> {  if (value === undefined || value === null) {    throw new Error(`${name} is not set`);  }} const port = process.env.PORT;assertDefined(port, "PORT");// from here on port: stringconsole.log(Number.parseInt(port, 10) + 1);
textexample output
8081

Where narrowing is lost

Narrowing holds as long as the compiler is sure the value has not changed. For a parameter or a let variable it is preserved in a callback created after the last assignment (since TypeScript 5.4). But if a variable is modified inside some nested function, the compiler cannot tell when that function will run, so callbacks see the full type again.

typescriptclosures.ts
function pageUrls(base: string | URL, pages: string[]): string[] {  if (typeof base === "string") {    base = new URL(base);  }  // no more assignments: inside the callback base is a URL  return pages.map((page) => `${base.origin}/${page}`);} console.log(pageUrls("https://example.com/docs", ["news", "faq"]));
textexample output
[ 'https://example.com/news', 'https://example.com/faq' ]

If narrowing is still lost, copy the checked value into a const before the callback: nobody can reassign a constant, so its type stays narrow.

Section sources

the section is written from these pages

Functions

A function type describes its parameters and result: (name: string) => string. Write parameter types explicitly, except in callbacks, where the context supplies them. TypeScript infers the result type from return, but some projects write it explicitly, as documentation and to avoid changing the result by accident.

typescriptprice.ts
function formatPrice(amount: number, currency = "UZS"): string {  return `${amount.toFixed(2)} ${currency}`;} const formatUsd = (amount: number): string => formatPrice(amount, "USD"); console.log(formatPrice(15000), formatUsd(9.5));
textexample output
15000.00 UZS 9.50 USD

Function types and signatures

Write a function type with an arrow: (value: number) => string. The parameter name is required: (string) => void is a function with a parameter named string of type any, which is an error under noImplicitAny. If a function also has properties, use a call signature in an object type. For calls with new, write a construct signature: { new (name: string): User }.

typescriptsignatures.ts
type Formatter = (value: number) => string; type Validator = {  description: string;  (input: string): boolean;}; const percent: Formatter = (value) => `${Math.round(value * 100)}%`; function isEmail(input: string): boolean {  return input.includes("@");}isEmail.description = "email address"; const check: Validator = isEmail;console.log(percent(0.257), check("a@example.com"), check.description);
textexample output
26% true email address

Optional and rest parameters

A parameter with ? can be omitted; inside the function its type is T | undefined. A default value also makes a parameter optional, but inside the function the type no longer includes undefined. A rest parameter ...values: number[] collects the remaining arguments into an array.

typescriptparams.ts
function greet(name?: string): string {  return `Salom, ${name ?? "mehmon"}!`;} function repeat(text: string, times = 2): string {  return text.repeat(times);} function sum(...values: number[]): number {  return values.reduce((total, v) => total + v, 0);} console.log(greet(), repeat("ab"), sum(1, 2, 3));
textexample output
Salom, mehmon! abab 6

An array that is spread into arguments must be a tuple or go into a rest parameter. const args = [8, 5] has the type number[], so Math.atan2(...args) does not compile; with const args = [8, 5] as const the type becomes a tuple of two numbers and the call passes.

Overloads

Overloads describe several ways to call one function: first come the signatures without a body, then a single implementation. The implementation signature is not visible from outside: you can call the function only in the ways the overloads allow.

typescriptoverloads.ts
function makeDate(timestamp: number): Date;function makeDate(year: number, month: number, day: number): Date;function makeDate(a: number, month?: number, day?: number): Date {  if (month !== undefined && day !== undefined) {    return new Date(a, month, day);  }  return new Date(a);} console.log(makeDate(2026, 10, 1).getMonth());// error TS2575: no overload expects 2 arguments// makeDate(2026, 10);
textexample output
10

If overloads differ only in the type of one parameter, replace them with a union: function len(x: string | unknown[]). A function with overloads cannot be called with a value of type string | unknown[]: the compiler picks one overload, and none fits the whole type.

void and never as a result

void is the result of a function that returns nothing. It is not the same as undefined: a function with the contextual type () => void may return a value, which is simply ignored. That is why a forEach callback that returns the result of push() compiles. A function declared directly with : void cannot return a value. never as a result means the function never completes normally, for example because it always throws.

typescriptvoid.ts
const source = [1, 2, 3];const copy: number[] = [];// the callback returns a number, but forEach expects () => void: allowedsource.forEach((n) => copy.push(n)); function fail(message: string): never {  throw new Error(message);} console.log(copy.length > 0 ? copy.length : fail("empty"));
textexample output
3

The this parameter

Declare the type of this as the first parameter: function (this: Button). This parameter is erased at compile time. It works only in regular functions: an arrow function takes this from the surrounding scope.

typescriptthis.ts
interface Button {  label: string;  onClick(handler: (this: Button) => void): void;} const save: Button = {  label: "Saqlash",  onClick(handler) {    handler.call(this);  },}; save.onClick(function () {  console.log(this.label);});
textexample output
Saqlash

Destructured parameters

Write the type after the whole destructuring pattern, and put default values inside the pattern. To avoid repeating the type, give it a name.

typescriptconnect.ts
type Options = { host: string; port?: number }; function connect({ host, port = 5432 }: Options): string {  return `${host}:${port}`;} console.log(connect({ host: "db.example.com" }));
textexample output
db.example.com:5432

Functions whose result type depends on the type of an argument, such as first<T>(items: T[]): T, are covered in the “Generics” section.

Section sources

the section is written from these pages

Objects, interfaces and classes

An object type lists its properties and their types: { id: number; email?: string }. You name such a type with interface or type, and TypeScript checks compatibility by the set of properties, not by the name of the type.

typescriptuser.ts
interface User {  readonly id: number;  name: string;  email?: string;  roles: string[];} function describe(user: User): string {  const contact = user.email ?? "no email";  return `${user.id}: ${user.name}, ${contact}`;} const admin: User = { id: 1, name: "Aziza", roles: ["admin"] };// error TS2540: id is read-only// admin.id = 2;console.log(describe(admin));
textexample output
1: Aziza, no email

Modifiers and dictionaries

SyntaxMeaning
email?: stringthe property may be absent; reading it gives string | undefined
readonly id: numberthe property cannot be reassigned after the object is created
[key: string]: numberan index signature: any string keys with numeric values
Record<string, number>the same, using a utility type
Record<"ru" | "uz", string>an object with exactly these keys, all required

Extending: extends and intersection

An interface inherits the properties of another through extends. For a type, the intersection & does the same: it combines the properties of several types. The difference shows up on conflict: the same property with different types in interfaces is an error at declaration, while in an intersection it gets the type never and no such object can be created.

typescriptextends.ts
interface Address {  city: string;  street: string;} interface Office extends Address {  floor: number;} type Timestamps = { createdAt: Date; updatedAt: Date };type StoredOffice = Office & Timestamps; const hq: StoredOffice = {  city: "Toshkent",  street: "Amir Temur",  floor: 5,  createdAt: new Date(0),  updatedAt: new Date(0),};console.log(hq.city, hq.floor);
textexample output
Toshkent 5

interface or type

Featureinterfacetype
Describe the shape of an objectyesyes
Name a union, primitive or tuplenoyes: type Id = string | number
Extendextendsintersection &
Add to it with a repeated declaration (declaration merging)yes: the properties are mergedno: Duplicate identifier error
Checking speedthe compiler caches relations between interfaces, so checking is usually fasterintersections are merged recursively and checked more slowly

Use interface for objects and classes until you need something only type can do: unions, tuples, conditional and mapped types.

Excess property checks

An object literal written directly where a type is expected is checked more strictly: a property that is not in the type is treated as a typo. The same object stored in a variable passes if at least one property matches: structural compatibility does not require an exact set of fields.

typescriptexcess.ts
interface SquareConfig {  color?: string;  width?: number;} function createSquare(config: SquareConfig): number {  return (config.width ?? 10) ** 2;} // error TS2561: 'colour' does not exist, did you mean 'color'?// createSquare({ colour: "red", width: 100 }); const options = { colour: "red", width: 100 };console.log(createSquare(options));
textexample output
10000

When called through a variable, the typo colour went unnoticed: the colour simply will not be applied. So an excess property error should almost always be fixed, not worked around.

Tuples and read-only arrays

A tuple is an array of known length with a type at each position: [string, number]. Elements can be optional ([number, number?]), and the end can hold a rest element ([string, ...number[]]). The types readonly string[] and readonly [number, number] forbid modifying the array; a literal with as const gets exactly this kind of type.

typescripttuples.ts
type Entry = [string, number]; function total(entries: readonly Entry[]): number {  return entries.reduce((sum, [, count]) => sum + count, 0);} const stock: Entry[] = [  ["olma", 12],  ["nok", 5],];console.log(total(stock)); // type of point: readonly [3, 4]const point = [3, 4] as const;console.log(point.length);
textexample output
172

A regular array can be passed where readonly is expected, but not the other way round: a function with a [number, number] parameter will not accept readonly [3, 4], because it could modify it.

Classes

Classes in TypeScript are JavaScript classes with types on fields and parameters. A field is declared with a type; under strictPropertyInitialization it must get a value in its declaration or in the constructor. implements checks that a class fits an interface but does not change the types of its methods.

typescriptwallet.ts
interface Account {  readonly id: number;  deposit(amount: number): void;} class Wallet implements Account {  readonly id: number;  private balance = 0;  #history: number[] = [];   constructor(id: number) {    this.id = id;  }   deposit(amount: number): void {    this.balance += amount;    this.#history.push(amount);  }   get total(): number {    return this.balance;  }} const wallet = new Wallet(1);wallet.deposit(500);console.log(wallet.total);
textexample output
500
ModifierAccessible fromAt run time
public (default)anywherea regular property
protectedthe class and its subclassesa regular property
privatethe class onlya regular property: the restriction exists only during checking, and wallet["balance"] passes
#historythe class onlya JavaScript private field: inaccessible from outside

Parameter properties are a short form, constructor(private readonly id: number) {}, that declares a field and assigns the argument to it. This form generates assignment code, so it is not erasable syntax, which is covered in the “Installation and first run” section.

An abstract class (abstract class) cannot be instantiated with new: it defines shared methods and abstract members that subclasses must implement.

typescriptreport.ts
abstract class Report {  abstract title(): string;   render(): string {    return `# ${this.title()}`;  }} class SalesReport extends Report {  title(): string {    return "October sales";  }} console.log(new SalesReport().render());
textexample output
# October sales

Section sources

the section is written from these pages

Generics

A generic is a function or type with a type parameter <T> that is filled in when you use it. It links the input and output types: first<T>(items: T[]) returns the same type that the array holds, not any.

typescriptfirst.ts
function first<T>(items: T[]): T | undefined {  return items[0];} const name = first(["Ali", "Vali"]);const port = first([8080, 8443]);console.log(name?.toUpperCase(), port?.toFixed(1));
textexample output
ALI 8080.0

The type parameter is usually inferred from the arguments, as here: name has the type string | undefined and port has number | undefined. Specify it explicitly in angle brackets when inference falls short or you need a wider type.

typescriptcombine.ts
function combine<T>(a: T[], b: T[]): T[] {  return a.concat(b);} // error TS2322: T was inferred as number from the first array// combine([1, 2], ["a"]);const mixed = combine<string | number>([1, 2], ["a"]);console.log(mixed);
textexample output
[ 1, 2, 'a' ]

Constraints

The constraint T extends { length: number } accepts only types with a length property and lets you use it inside the function. K extends keyof T links two parameters: the key must be among the object’s keys, and the result T[K] gets the type of exactly that property.

typescriptconstraints.ts
function longest<T extends { length: number }>(a: T, b: T): T {  return a.length >= b.length ? a : b;} function pick<T, K extends keyof T>(obj: T, key: K): T[K] {  return obj[key];} const user = { id: 7, name: "Aziza" };console.log(longest("olma", "nok"), longest([1, 2], [3]));console.log(pick(user, "name").toUpperCase());// error TS2345: user has no key 'email'// pick(user, "email");
textexample output
olma [ 1, 2 ]AZIZA

Generic interfaces, types and classes

typescriptresult.ts
interface ApiResponse<T> {  data: T;  status: number;} type Result<T, E = Error> =  | { ok: true; value: T }  | { ok: false; error: E }; function parsePort(text: string): Result<number> {  const port = Number(text);  return Number.isInteger(port)    ? { ok: true, value: port }    : { ok: false, error: new Error(`Not a port: ${text}`) };} const langs: ApiResponse<string[]> = { data: ["ru", "uz"], status: 200 };const parsed = parsePort("8080");if (parsed.ok) {  console.log(langs.data.join(", "), parsed.value + 1);}
textexample output
ru, uz 8081

In Result<T, E = Error> the second parameter has a default: Result<number> is the same as Result<number, Error>. Parameters with defaults come after required ones, and the default must satisfy the parameter’s constraint. Classes can be generic too: class Cache<T>. A type parameter applies only to instances: static members of a class cannot use it.

const type parameters

The const modifier before a type parameter (since TypeScript 5.0) asks for the most precise type to be inferred from the argument, as if the caller had written as const: the array is inferred as a tuple even without as const. A constraint to a readonly array makes the tuple readonly; without it the tuple stays mutable, and without const on the parameter a regular array is inferred instead of a tuple.

typescriptroutes.ts
function routes<const T extends readonly string[]>(paths: T): T {  return paths;} // type of all: readonly ["/", "/news", "/about"]const all = routes(["/", "/news", "/about"]);type Route = (typeof all)[number];const home: Route = "/";console.log(home, all.length);
textexample output
/ 3

When you don’t need a generic

  • If the type parameter appears only once in the signature, it links nothing: write greet(s: string) instead of greet<S extends string>(s: S).
  • Use the parameter itself, not its constraint: first<T>(arr: T[]) infers the element type, while first<T extends any[]>(arr: T) returns any.
  • The fewer type parameters, the better the inference: a parameter F extends (x: T) => boolean instead of a plain callback type only forces callers to supply an extra type argument.
  • If a function accepts a value of one of several types and the result type does not depend on it, a union is enough: len(x: string | unknown[]): number.

Section sources

the section is written from these pages

Type manipulation

Type operations build a new type from an existing one: keyof gives a union of keys, T["id"] gives the type of a property, a conditional type picks a variant, and a mapped type walks over every property. This keeps the description of your data in one place, so derived types never drift away from it.

keyof, typeof and indexed access

In a type position, typeof takes the type of a variable or property, keyof gives a union of keys, and an indexed access type such as Config["port"] gives the type of a single property. Indexing with number gives the element type of an array: (typeof users)[number].

typescriptconfig.ts
const config = {  host: "localhost",  port: 5432,  ssl: false,}; type Config = typeof config;// "host" | "port" | "ssl"type ConfigKey = keyof Config;// numbertype Port = Config["port"]; function read<K extends ConfigKey>(key: K): Config[K] {  return config[key];} const port: Port = read("port");console.log(port + 1);
textexample output
5433

Conditional types and infer

A conditional type T extends U ? X : Y gives X if T is assignable to U, and Y otherwise. Inside the condition, infer declares a type variable that the compiler extracts from the matched structure. A conditional type is distributive: applied to a union, it runs on each member separately. To prevent that, wrap both sides of extends in square brackets.

typescriptconditional.ts
type Unwrap<T> = T extends Promise<infer V> ? V : T;type ElementOf<T> = T extends (infer E)[] ? E : never;type ToArray<T> = T extends unknown ? T[] : never;type ToArrayOnce<T> = [T] extends [unknown] ? T[] : never; // stringtype A = Unwrap<Promise<string>>;// numbertype B = ElementOf<number[]>;// string[] | number[]type C = ToArray<string | number>;// (string | number)[]type D = ToArrayOnce<string | number>; const sample: [A, B, C, D] = ["ok", 1, ["x"], [1, "x"]];console.log(sample.length);
textexample output
4

Mapped types

A mapped type { [K in keyof T]: … } iterates over keys and builds the type of each property. The readonly and ? modifiers are added or removed with + and -, and as renames keys or drops them when the result is never. This is how the built-in utility types Partial, Readonly and Pick work:

typescriptmapped.ts
type MyPartial<T> = { [K in keyof T]?: T[K] };type MyPick<T, K extends keyof T> = { [P in K]: T[P] };type Mutable<T> = { -readonly [K in keyof T]: T[K] };type Getters<T> = {  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];}; interface User {  readonly id: number;  name: string;} const draft: MyPartial<User> = { name: "Aziza" };const card: MyPick<User, "name"> = { name: "Aziza" };const editable: Mutable<User> = { id: 1, name: "Aziza" };editable.id = 2;const getters: Getters<User> = { getId: () => 2, getName: () => "Aziza" };console.log(draft.name, card.name, editable.id, getters.getName());
textexample output
Aziza Aziza 2 Aziza

Template literal types

A template literal type is written like a JavaScript template string, but in a type position. Unions inside it are multiplied out: two languages and three keys give six strings. The built-in Uppercase, Lowercase, Capitalize and Uncapitalize change the case.

typescriptevents.ts
type Lang = "ru" | "uz";type Key = "title" | "summary" | "body";// "ru_title" | "ru_summary" | ... — 6 strings in totaltype MessageId = `${Lang}_${Key}`; type Watched<T> = {  on(event: `${string & keyof T}Changed`, cb: () => void): void;}; function watch<T extends object>(obj: T): T & Watched<T> {  return { ...obj, on: () => {} };} const user = watch({ name: "Aziza", age: 30 });user.on("nameChanged", () => {});// error TS2345: expected "nameChanged" | "ageChanged"// user.on("name", () => {}); const id: MessageId = "uz_title";console.log(id);
textexample output
uz_title

Section sources

the section is written from these pages

Modules and declaration files

TypeScript does not load modules itself: it mirrors the rules of the environment where the code will run, either Node.js or a bundler. So choose module and moduleResolution in tsconfig.json to match the runtime, otherwise the check will accept an import that fails at run time.

A module is a file with a top-level import or export. For each import, the compiler has three questions to answer: what format the output file will have (ESM or CommonJS), whether the import will be found at run time, and what types the imported names have. Finding a file from an import path is called module resolution. The compiler never rewrites the path: the .js output contains exactly what is written in the .ts file.

Which settings to choose

Where the code runsmodulemoduleResolutionAlso needed
Node.js runs the .js output of tscnodenextnodenext, set automatically"type": "module" in package.json if you need ESM
A bundler: webpack, esbuild and othersesnext or preservebundler"noEmit": true: the bundler produces the files
A library for npmnode18 or nodenextfollows module"declaration": true and "strict": true

For code that Node.js runs, only node16, node18 and nodenext are correct, even if all of your code is ESM: with esnext the output files may be identical, but imports are checked differently. In a project with a bundler, the documentation does not yet recommend setting "type": "module": some bundlers then link ESM and CommonJS differently, and TypeScript does not model that.

File extensions in imports

Under nodenext, the file format is determined as in Node.js: .mts is always ESM, .cts is always CommonJS, and .ts is ESM if the nearest package.json has "type": "module", and CommonJS otherwise. In ESM, a relative import is written with the extension of the output file, .js, even though the file next to it is .ts: during lookup the compiler substitutes the source file.

typescriptsrc/slug.ts
export function slug(title: string): string {  return title.trim().toLowerCase().replaceAll(" ", "-");}
typescriptsrc/main.ts
import { slug } from "./slug.js"; console.log(slug("Yangi reliz"));
textexample output
yangi-reliz

With moduleResolution: bundler, you can write imports without an extension and import a directory containing index.ts, which is how bundlers resolve modules. Node.js ESM imports do not allow this.

How package types are found

For an import from "pkg", the compiler looks through the node_modules directories and first looks for types in the package itself: through the exports field with the types condition, or through the types and main fields of its package.json. Then it looks for a separate @types/pkg package. Only if no types are found anywhere does it fall back to the .js file without types: the import gets the type any, which is an error under noImplicitAny. For the relative path ./util.js, the compiler tries ./util.ts and ./util.tsx first, then ./util.d.ts.

The lookup order is the same for nodenext and bundler; only the conditions used to select an entry in exports differ.

Type-only imports

Import a name that is only needed as a type with import type, or mark the individual name with type. With verbatimModuleSyntax, the compiler keeps every import without type in the .js output as written, and treats an unmarked import of only types as an error. This way tsc, bundlers and Node.js, which strips types itself, all read the code the same way.

typescriptsrc/main.ts
import type { User } from "./types.js";import { loadUser, type LoadOptions } from "./api.js"; // error TS1484: User is a type, use import type// import { User } from "./types.js"; const options: LoadOptions = { cache: false };const user: User = await loadUser(7, options);console.log(user.name);
textexample output
Aziza

Declaration files and @types packages

A declaration file, .d.ts, contains only types and describes a neighbouring .js file. Many npm packages ship their own .d.ts files. For the rest, types are published separately in packages with the @types/ prefix and installed as a dev dependency; if a package has its own types, you do not need @types.

bashin the terminal
npm install -D @types/lodash

Since TypeScript 6.0, @types packages that add global names, such as process from @types/node or describe and it from test frameworks, must be listed in types: by default the list is empty. Imported modules are found without it.

jsontsconfig.json
{  "compilerOptions": {    "types": ["node", "jest"]  }}

For a module without types, write the declarations yourself in a .d.ts file that is part of the project. That file must not have a top-level import or export: otherwise declare module augments an existing module instead of declaring a new one.

typescriptsrc/types/legacy-pay.d.ts
declare module "legacy-pay" {  export function charge(amount: number): Promise<string>;}
typescriptsrc/pay.ts
import { charge } from "legacy-pay"; const receipt: string = await charge(15000);console.log(receipt);

Path aliases

paths maps an import to project files: "@/*": ["./src/*"]. Paths are resolved relative to the directory of tsconfig.json; baseUrl is not needed for this, and the option was removed in 7.0. paths does not change imports in the output .js, so the runtime must understand the same alias. In a project with a bundler, configure it in the bundler as well:

jsontsconfig.json
{  "compilerOptions": {    "module": "preserve",    "moduleResolution": "bundler",    "noEmit": true,    "paths": {      "@/*": ["./src/*"]    }  }}
typescriptsrc/page.ts
import { slug } from "@/slug"; console.log(slug("Bosh sahifa"));

For Node.js, use the imports field in package.json instead of paths: its names start with #, and both Node.js and TypeScript understand them. Point the path at the output file in dist, and the compiler will find the source through rootDir and outDir.

jsonpackage.json
{  "type": "module",  "imports": {    "#lib/*": "./dist/lib/*"  }}
typescriptsrc/main.ts
import { slug } from "#lib/slug.js"; console.log(slug("Narxlar"));
textexample output
narxlar

Section sources

the section is written from these pages

Configuring tsconfig.json

tsconfig.json marks the root of a TypeScript project: it lists the project’s files and the compiler options. Run without arguments, tsc looks for this file in the current directory and then up the directory tree, and npx tsc --showConfig prints the final settings after all inheritance.

File structure

jsontsconfig.json
{  "extends": "./tsconfig.base.json",  "compilerOptions": {    "rootDir": "./src",    "outDir": "./dist",    "types": ["node"]  },  "include": ["src"],  "exclude": ["src/**/*.test.ts"]}
KeyWhat it sets
compilerOptionscompiler options; if the key is missing, the defaults apply
includepatterns for the project’s files; **/* by default if there is no files
excludewhat to remove from include; by default node_modules, bower_components, jspm_packages and outDir
filesan explicit list of files, for small projects
extendsthe file to inherit settings from
referencesthe projects this one depends on: tsc -b builds them first

Main options

OptionWhat it doesDefault
strictenables all strict checks: noImplicitAny, strictNullChecks and otherstrue
targetthe JavaScript version of the output and the built-in types for itthe latest stable ECMAScript edition
modulethe module format of the output and the runtime rulesesnext
moduleResolutionhow to look up imported modulesfollows module
libbuilt-in declarations, for example es2025 and domthe set for target, plus the browser types dom
typeswhich @types packages to include without importing them[]
rootDirthe root of the sources: the directory structure in outDir is built relative to itthe directory of tsconfig.json
outDirthe directory for .js, .d.ts and source mapsnext to the sources
noEmittype-check only, no files are writtenfalse
declarationemit .d.ts filesfalse; true with composite
skipLibCheckskip checking library .d.ts files: faster, but errors in their types go unnoticedfalse
noUncheckedIndexedAccessreading arr[i] or obj[key] through an index signature adds undefined to the typefalse
verbatimModuleSyntaximports without type are kept in the output as written, and importing only types requires typefalse
isolatedModulesforbids anything that cannot be compiled one file at a timetrue with verbatimModuleSyntax
erasableSyntaxOnlyforbids enum, namespace with code, and parameter propertiesfalse

Defaults that changed in 6.0

TypeScript 6.0 changed the default value of several options, and 7.0 kept the change. If your project relied on the old behaviour, set the option explicitly:

  • strict is true: strict checks are on unless you write "strict": false
  • module is esnext, and target is the latest stable ECMAScript edition
  • noUncheckedSideEffectImports is true: for a side-effect import such as import "./polyfill.js", the compiler checks that the file exists
  • rootDir is the directory of tsconfig.json: if your sources are in src, without "rootDir": "./src" the files end up in dist/src/
  • types is []: list global types such as @types/node explicitly, and ["*"] restores the old behaviour of including every @types package
jsontsconfig.json
{  "compilerOptions": {    "rootDir": "./src",    "outDir": "./dist",    "types": ["node"]  },  "include": ["src"]}

Options and values that 6.0 deprecated became errors in 7.0: target: es5, downlevelIteration, moduleResolution: node10 and classic, module: amd, umd, systemjs and none, baseUrl, esModuleInterop: false and others. In 6.0 you could still keep them with "ignoreDeprecations": "6.0", while outFile had already been removed in 6.0. For the list and the replacements, see the “Versions and what’s new” section.

Inheriting settings

extends takes settings from another file, and the options in the current file override them. files, include and exclude in the inheriting file replace the base ones entirely, and references are not inherited at all. Relative paths are resolved from the file in which they are written. This lets you keep a monorepo’s shared rules in a single tsconfig.base.json.

jsontsconfig.base.json
{  "compilerOptions": {    "module": "nodenext",    "target": "esnext",    "strict": true,    "verbatimModuleSyntax": true,    "skipLibCheck": true  }}

Project references and tsc -b

A large codebase is split into projects, each with its own tsconfig.json, and linked with project references. A referenced project enables composite: then declaration is on, rootDir defaults to its directory, and all files must be matched by include. An import from such a project reads its prebuilt .d.ts files, so checking the dependent project is faster.

textproject structure
packages/├── tsconfig.json├── shared/│   ├── tsconfig.json│   └── src/index.ts└── api/    ├── tsconfig.json    └── src/main.ts
jsonshared/tsconfig.json
{  "compilerOptions": {    "composite": true,    "module": "nodenext",    "rootDir": "./src",    "outDir": "./dist"  },  "include": ["src"]}
jsonapi/tsconfig.json
{  "compilerOptions": {    "module": "nodenext",    "rootDir": "./src",    "outDir": "./dist"  },  "include": ["src"],  "references": [{ "path": "../shared" }]}
jsontsconfig.json
{  "files": [],  "references": [{ "path": "./shared" }, { "path": "./api" }]}

The root file with an empty files only lists the projects, so that their files are not compiled twice. In api, a module from shared is imported by the path to its output file: import { slug } from "../../shared/dist/index.js".

bashin the packages directory
# build out-of-date projects in dependency ordernpx tsc -b# the same, explaining what is built and whynpx tsc -b --verbose# delete the build output of all projectsnpx tsc -b --clean

tsc -b works out the order itself and skips projects that have not changed. It does not write files when there are errors: in this mode noEmitOnError applies to all projects.

Checking the final settings

bashin the terminal
# all options after extends and defaultsnpx tsc --showConfig# why each file is part of the projectnpx tsc --explainFiles --noEmit# only the list of project filesnpx tsc --listFilesOnly

Section sources

the section is written from these pages

Common errors and troubleshooting

Start with npx tsc --noEmit: it checks the whole project the same way CI does. Read a message from top to bottom: the first line says what is wrong, and each indented line answers the question “why?”. If an error does not appear where you expect it, compare your settings with npx tsc --showConfig.

Steps to follow:

  1. Make sure you are running the right version: npx tsc --version.
  2. Run npx tsc --noEmit and start with the first error: the ones after it often follow from it.
  3. Read the message and its details down to the deepest line, which names the specific field or value.
  4. If the error is about settings or module lookup, run npx tsc --showConfig and npx tsc --traceResolution.
  5. Do not silence the error with any, as or // @ts-ignore: the type stops being checked, but the problem stays.

Argument of type 'number' is not assignable to parameter of type 'string'.

Cause: the type of the argument does not match the type of the parameter. In messages, “assignable” means “can be used in place of”; if the relation does not hold, the lines below explain exactly why.

bashin the terminal
npx tsc --noEmit
textexample output
src/app.ts:6:19 - error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. 6 console.log(greet(userId));                    ~~~~~~ Found 1 error in src/app.ts:6
typescriptsrc/app.ts
function greet(name: string): string {  return `Salom, ${name}!`;} const userId = 42;// convert the value explicitly or fix the parameter typeconsole.log(greet(String(userId)));

'obj.last' is possibly 'undefined'.

Cause: the value may be missing, for example because it is an optional property or parameter. With strictNullChecks, the compiler requires you to check it before use: with a comparison, the ?. operator, or a default value via ??.

typescriptprint-name.ts
function printName(obj: { first: string; last?: string }) {  if (obj.last !== undefined) {    console.log(obj.last.toUpperCase());  }  console.log(obj.last?.toUpperCase() ?? obj.first);} printName({ first: "Aziza" });

Property 'toUpperCase' does not exist on type 'string | number'.

Cause: not every member of the union has the property, and the compiler does not know which one it is right now. Narrow the type with a check. If the property is missing from the type altogether, check the name for a typo or extend the type.

typescriptprint-id.ts
function printId(id: string | number) {  if (typeof id === "string") {    console.log(id.toUpperCase());  } else {    console.log(id.toFixed(0));  }} printId("ab12");

Object literal may only specify known properties, and 'username' does not exist in type 'User'.

Cause: the object literal has a field that is not in the type, most often a typo or an old field name. Fix the name. If extra fields really are expected, add them to the type or add an index signature [key: string]: unknown.

typescriptuser.ts
interface User {  name: string;  id: number;} const user: User = {  name: "Hayes",  id: 0,};console.log(user.name);

Cannot find name 'process'. Do you need to install type definitions for node?

Cause: the Node.js global types are not included. Either @types/node is not in devDependencies, or it is not listed in types: since TypeScript 6.0 that list is empty by default. Errors for describe and it from test frameworks look the same.

bashin the terminal
npm ls @types/nodenpx tsc --showConfig
bashin the terminal
npm install -D @types/node
jsontsconfig.json
{  "compilerOptions": {    "types": ["node"]  }}

Cannot find module '...' or its corresponding type declarations.

Cause: the compiler could not find the module or its types. The package is not installed; it has no types of its own and there is no @types package; moduleResolution does not match the environment; or an alias from paths is not configured. --traceResolution shows every path the compiler tried and the final result.

bashin the terminal
npm ls lodashnpx tsc --noEmit --traceResolution > resolution.txt
  • The package is missing: install it with npm install lodash.
  • The package has no types: install a types package if one exists (npm install -D @types/lodash), or declare the module in your own .d.ts file.
  • The module is looked up in the wrong place: check module and moduleResolution against the environment where the code runs.
  • The import uses an alias: check paths in tsconfig.json and the same alias in the bundler.

error TS5112: tsconfig.json is present but will not be loaded if files are specified on commandline. Use '--ignoreConfig' to skip this error.

Cause: tsc was run with a file name in a directory that contains tsconfig.json. Since TypeScript 6.0 this is an error: previously the project settings were silently ignored in this case.

bashin the terminal
# the whole project, with the settings from tsconfig.jsonnpx tsc# a single file, ignoring tsconfig.json, with default settingsnpx tsc --ignoreConfig src/index.ts

Minor problems

SymptomCauseWhat to do
The files ended up in dist/src/ instead of dist/since 6.0, rootDir defaults to the directory of tsconfig.jsonset "rootDir": "./src"
After upgrading to 7.0, tsc reports that an option was removedthe option was deprecated in 6.0 and removed in 7.0remove it or replace it as described in the “Versions and what’s new” section
The editor shows different errors from tsc in CIdifferent TypeScript versions or different settingscompare npx tsc --version and npx tsc --showConfig in both places
node src/index.ts fails with ERR_UNSUPPORTED_TYPESCRIPT_SYNTAXthe file uses enum, namespace with code, or parameter propertiesreplace them and enable erasableSyntaxOnly so that tsc catches such code in advance
The code runs in Node.js, but tsc fails in CINode.js does not check typesrun npx tsc --noEmit before committing
An import from a package has type anythe package has no types and strict is offinstall the @types package or declare the module in a .d.ts file, as described in “Modules and declaration files”
tsc finished without errors, but there are no output filesnoEmit is on, or the files are not matched by includecheck npx tsc --showConfig and npx tsc --explainFiles

Section sources

the section is written from these pages

Versions and what’s new

This reference covers TypeScript 7.0, the compiler rewritten in Go. The latest release is 7.0.2, published on 8 July 2026. New versions arrive roughly every 3–4 months, each preceded by a beta and an RC. Only the current branch receives fixes, and TypeScript does not publish support timelines.

The beta gets the number X.Y.0, the RC gets X.Y.1, and the first stable release is X.Y.2. So 7.0.2 is the 7.0 release itself, not a fix for it. At the end of each month the team decides whether the current branch needs a patch.

BranchStatusFirst stable releaseLatest release
7.1beta, not for production—7.1.0-beta — 20 October 2026
7.0current, covered here7.0.2 — 8 July 20267.0.2 — 8 July 2026
6.0last JavaScript-based version, no releases since April 20266.0.2 — 23 March 20266.0.3 — 16 April 2026

6.0 is kept alongside 7.0 for tools that need the compiler API, which 7.0 does not have. The @typescript/typescript6 package contains the 6.0 compiler as tsc6 together with its API, so both versions can be installed in one project without conflict.

What changed in 7.0

  • Installation and first run: the compiler is a native Go program; a full build is typically 8–12 times faster than in 6.0 and uses less memory. It is installed with the same typescript package, and --watch mode has been rewritten to use fewer resources.
  • Configuring tsconfig.json: the 6.0 defaults (strict, module, target, rootDir, types) apply, and options deprecated in 6.0 are now errors.
  • Basic types: the order of union members in .d.ts files and messages no longer depends on declaration order in the program (stableTypeOrdering is always on), so 6.0 and 7.0 output can differ in ordering.
  • Configuring tsconfig.json: type checking runs in parallel, with 4 workers by default. The experimental --checkers flag sets their number, --builders sets how many projects tsc -b builds at once, and --singleThreaded turns parallelism off.
  • Type operations: inference from template literal types splits a string by Unicode code points, so the first character of "😀abc" is "😀", not half of a surrogate pair.
  • JavaScript checking (checkJs) is closer to the .ts rules: @enum, @class, Closure function syntax such as function(string): void, and constructor functions via prototype are not supported.

Deprecated and removed

These options and constructs were deprecated in 6.0, and the warnings could be silenced with "ignoreDeprecations": "6.0". In 7.0 each of them is an error:

Removed in 7.0Replacement
target: es5, downlevelIterationtarget of es2015 or higher; use an external compiler for ES5
moduleResolution: node (node10) and classicnodenext for Node.js, bundler for a bundler
module: amd, umd, systemjs, noneesnext or preserve together with a bundler
baseUrlpaths in paths relative to the project root: "@app/*": ["./src/app/*"]
outFile (already removed in 6.0)a bundler
esModuleInterop: false, allowSyntheticDefaultImports: falseremove the option; use import express from "express" instead of import * as express
alwaysStrict: falseremove the option; rename identifiers such as await and static
module Foo { } for a namespacenamespace Foo { }
import … asserts { type: "json" }import … with { type: "json" }
/// <reference no-default-lib="true"/>the noLib or libReplacement options
tsc app.ts in a directory with tsconfig.jsontsc or tsc --ignoreConfig app.ts

How to upgrade

  1. Upgrade to 6.0: npm install -D typescript@6. Remove all deprecation warnings without silencing them via ignoreDeprecations: these options do not exist in 7.0.
  2. If files start being emitted to different directories or global names disappear, set rootDir and types explicitly; these are the two most common changes.
  3. To compare 6.0 and 7.0 output, temporarily enable --stableTypeOrdering in 6.0 so that type order matches 7.0. The flag slows checking by up to 25%, so don’t leave it on.
  4. Install 7.0: npm install -D typescript@7, then run npx tsc --noEmit.
  5. If your tools need the compiler API, such as typescript-eslint, keep 6.0 for them via the @typescript/typescript6 package and use tsc from 7.0.
jsonpackage.json
{  "devDependencies": {    "@typescript/native": "npm:typescript@^7.0.0",    "typescript": "npm:@typescript/typescript6@^6.0.0"  }}

Tools import 6.0 under the usual name typescript, while npx tsc runs the 7.0 compiler. Projects using Vue, Svelte, Astro and MDX stay on 6.0 for now: their editor support needs the compiler API. In Angular, you can check the project with tsc from 7.0 and keep 6.0 in the editor.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “TypeScript” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61