TypeScript в браузерной игре: типы сущностей, строгий режим и быстрая сборка

Коротко

TypeScript проверяет браузерную игру до запуска: сущности уровня описываются дискриминируемым объединением по полю kind, а функция assertNever превращает забытую ветку switch в ошибку компиляции. strict ловит неявный any и undefined, но noUncheckedIndexedAccess и exactOptionalPropertyTypes включаются отдельно. Типы не проверяют данные во время исполнения, поэтому JSON уровня проверяют кодом на входе. Сборку делят надвое: esbuild или Node.js 24 стирают типы, а tsc --noEmit отдельно их проверяет.

Содержание

  1. Что TypeScript даёт игре и чего не даёт
  2. Версии и tsconfig.json
  3. Типы сущностей: дискриминируемое объединение
  4. Строгий режим: что входит в strict
  5. as, ! и any гасят ошибку, но не падение
  6. JSON уровня: проверка на входе
  7. Быстрая сборка: проверка отдельно, стирание типов отдельно
  8. Код игры
  9. Файлы ловушек
  10. Проверка одним скриптом
  11. Что показал прогон
  12. Время проверки и сборки
  13. Что не подтвердилось
  14. Практический сценарий: в игру добавили пружину
  15. Когда вам это не подойдёт

Что TypeScript даёт игре и чего не даёт

TypeScript проверяет код до запуска и ничего не добавляет к самой игре: перед выполнением типы стираются, и в браузер уходит обычный JavaScript. Опечатку в поле, забытую ветку для нового врага или обращение к объекту, которого может не быть, компилятор покажет сразу, а строку вместо числа в JSON уровня — нет.

Пример — комната, где игрок собирает монеты, берёт ключ и открывает дверь, а по полу ходит враг-«ходок». Шаг 1/60 с устроен как в статье про игровой цикл.

Версии и tsconfig.json

Пример проверен на TypeScript 7.0.2, esbuild 0.28.2, @types/node 24.19.2 и Node.js 24.22.1 (версии из package-lock.json и строки 0 вывода). TypeScript 7.0 — первая стабильная версия компилятора, переписанного на Go; по заметке к выпуску от 8 июля 2026 года она совместима по проверке типов с 6.0 и берёт его значения по умолчанию: strict включён, module — esnext, types — пустой список.

npm install --save-dev --save-exact typescript esbuild @types/node@24
{
  "name": "code-71",
  "scripts": {
    "check": "tsc --noEmit -p .",
    "build": "esbuild src/main.ts --bundle --format=esm --outfile=dist/game.js",
    "test": "node test/run.ts"
  },
  "type": "module",
  "devDependencies": {
    "@types/node": "24.19.2",
    "esbuild": "0.28.2",
    "typescript": "7.0.2"
  },
  "private": true
}
{
  "compilerOptions": {
    "target": "es2022",
    "lib": ["es2023", "dom"],
    "module": "nodenext",
    "types": ["node"],
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "isolatedModules": true,
    "verbatimModuleSyntax": true,
    "erasableSyntaxOnly": true,
    "skipLibCheck": true
  },
  "include": ["src", "test"]
}
ФлагЧто проверяет (по справочнику tsconfig)
strictсемейство из девяти проверок, среди них noImplicitAny, strictNullChecks, strictPropertyInitialization
noUncheckedIndexedAccessдобавляет undefined к чтению по индексу
exactOptionalPropertyTypesзапрещает записывать undefined в необязательное поле
noImplicitReturns, noFallthroughCasesInSwitchпуть без return, провал в следующий case
isolatedModulesзапрещает то, что нельзя перевести по одному файлу
verbatimModuleSyntaxтребует import type для импорта только типов
erasableSyntaxOnlyзапрещает синтаксис, который нельзя просто стереть, например enum
allowImportingTsExtensionsразрешает import "./world.ts", только вместе с noEmit

Типы сущностей: дискриминируемое объединение

Сущность описывается объединением типов с общим полем-меткой kind, по которому TypeScript понимает, какие ещё поля есть у объекта.

Внутри case "coin": переменная e — уже Coin: e.value проходит, e.speed — ошибка, и общий тип со всеми полями не нужен. Тот же приём годится для состояний из статьи про конечный автомат и событий из статьи про издателя и подписчика. EntityKind = Entity["kind"] собирает все метки в "player" | "walker" | "coin" | "door" | "key".

Проверка полноты через never

assertNever(x: never) в ветке default делает забытый case ошибкой компиляции. Когда все типы разобраны, в default у e тип never; если добавить Spring и не дописать ветку, туда попадает Spring, и компилятор выдаёт TS2345. Во время исполнения assertNever бросает исключение — на случай сущности неизвестного типа из непроверенных данных.

Без default функция с результатом number даст TS2366 «нет завершающего return», а функция void, например шаг обновления, промолчит.

Список типов через Record

Список всех меток задают объектом Record<EntityKind, true>, а не массивом. Массив EntityKind[] компилятор примет и без нового типа — в нём может быть любое подмножество. У Record ключ обязателен для каждой метки, и забытый тип даёт TS2741.

Строгий режим: что входит в strict

strict включает девять проверок, но не noUncheckedIndexedAccess и не exactOptionalPropertyTypes. В справочнике tsconfig в его семействе перечислены alwaysStrict, strictNullChecks, strictBindCallApply, strictBuiltinIteratorReturn, strictFunctionTypes, strictPropertyInitialization, noImplicitAny, noImplicitThis и useUnknownInCatchVariables. Файл traps/flags.ts мы проверили четырьмя настройками:

НастройкаОшибокНовые коды
strict: false0—
strict: true4TS7006 ×2, TS2564, TS18048
+ noUncheckedIndexedAccess5TS18048 (third)
+ exactOptionalPropertyTypes6TS2375

Без strict файл компилируется чисто и падает при запуске: find не нашёл босса и вернул undefined.

noUncheckedIndexedAccess

Флаг делает результат чтения по индексу типом «значение или undefined». Без него waves[2] в массиве из двух волн — string[], с ним — TS18048. В игре это тайловая сетка, волны, кадры анимации; цена — лишние проверки там, где индекс заведомо в границах.

exactOptionalPropertyTypes

Флаг различает «поля нет» и «поле равно undefined»: target: undefined в поле target?: string даёт TS2375. Разница видна при сохранении: проверка "target" in enemy отвечает по-разному, а JSON.stringify, по MDN, поле со значением undefined пропускает. Из-за этого флага в level.ts дверь без ключа собирается отдельной веткой, без поля key.

as, ! и any гасят ошибку, но не падение

as, ! и any выключают проверку и ничего не меняют при запуске. В traps/escape.ts четыре обращения к врагу, которого нет: tsc нашёл 1 ошибку TS2532 — только у честной записи, а при запуске упали все 4. as и ! допустимы, только если значение проверено рядом в коде; вместо any берите unknown — к нему нельзя обратиться, пока тип не сужен.

JSON уровня: проверка на входе

Типы не проверяют данные во время исполнения, поэтому JSON уровня проверяют кодом при загрузке. JSON.parse в стандартной библиотеке TypeScript возвращает any, и JSON.parse(text) as Level компилятор примет при любом содержимом.

Что ломает непроверенный JSON

Непроверенный JSON ломает игру не сразу и не там, где ошибка. В data/level-bad.json три ручные правки: "value": "10" строкой, у ходока нет speed, у двери "lock" вместо "locked". Через as Level уровень прошёл проверку типов, а в игре счёт стал строкой «010525», ходок ушёл в x=NaN, дверь оказалась открытой без ключа, а описание игрока упало с TypeError: тип обещает keys, а в JSON этого поля нет.

parseLevel(unknown)

parseLevel принимает unknown и возвращает { ok: true, level } или { ok: false, errors } — тоже дискриминируемое объединение. Внутри нет as к типу уровня: каждое поле проверяется typeof, поэтому смена типа Coin покажет и место в загрузчике. На level-bad.json проверка вернула 3 ошибки с путём до поля.

Чего проверка формы не ловит

Проверка формы не ловит связей между объектами. В data/level-nokey.json все поля верны, но ключа red для двери нет: parseLevel принял файл, игрок застрял у двери на x=116. Ссылки и решаемость разобраны в статьях про связи объектов в данных уровня и дерево реплик в JSON, версии формата — в статье про сохранения.

Быстрая сборка: проверка отдельно, стирание типов отдельно

Быстрая сборка получается, если транспилятор только стирает типы по одному файлу, а tsc --noEmit проверяет весь проект отдельно.

esbuild не проверяет типы

esbuild выбрасывает типы без проверки; его документация прямо советует запускать tsc --noEmit параллельно. В traps/score.ts в addScore(score: number, bonus: number) передана строка "10": tsc даёт TS2345, esbuild собирает с 0 ошибок, игра выводит счёт: 510. Прямой node traps/score.ts — тоже 510.

isolatedModules и verbatimModuleSyntax

isolatedModules запрещает то, что нельзя правильно перевести по одному файлу; документация esbuild советует его включать. Пример — реэкспорт типа export { Enemy, MAX_HP } в traps/reexport/index.ts: без флагов 0 ошибок, с isolatedModules — TS1205, с verbatimModuleSyntax — TS1484 и TS1205. Node.js на этом файле падает с SyntaxError ... does not provide an export named 'Enemy', а esbuild с --bundle собрал его, и код вывел MAX_HP = 5: по документации esbuild в режиме сборки отсутствующие экспорты в TypeScript-файлах игнорируются. Лечится import type и export type.

Node.js 24 запускает .ts сам

По документации Node.js стирание типов включено по умолчанию с версии 23.6.0 и стабильно с 24.12.0. Node.js заменяет типы пробелами, не проверяет их и не читает tsconfig.json; enum, namespace с кодом и свойства в параметрах конструктора без флага --experimental-transform-types дают ошибку. node traps/enum.ts упал с ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX, а tsc с erasableSyntaxOnly заранее показал TS1294; esbuild enum переводит (enum: 1). Ещё по документации: расширение .ts в import обязательно. Вместо enum подходит объект as const.

Итоговая схема: npm run build — при каждом сохранении, npm run check — перед коммитом и в CI, npm test — логика в Node.js без сборки; в публикацию идёт только то, что прошло check с 0 ошибок.

Код игры

Логика — три файла без браузерных API, обвязка для браузера — src/main.ts.

// src/entities.ts — типы сущностей уровня
export type Vec = { x: number; y: number };

export type Player = { kind: "player"; id: string; pos: Vec; speed: number; keys: string[] };
export type Walker = { kind: "walker"; id: string; pos: Vec; speed: number; dir: 1 | -1 };
export type Coin = { kind: "coin"; id: string; pos: Vec; value: number; taken: boolean };
export type Door = { kind: "door"; id: string; pos: Vec; locked: boolean; key?: string };
export type Key = { kind: "key"; id: string; pos: Vec; taken: boolean };

export type Entity = Player | Walker | Coin | Door | Key;
export type EntityKind = Entity["kind"];

export function assertNever(x: never): never {
  throw new Error("неизвестный тип сущности: " + JSON.stringify(x));
}

export function describe(e: Entity): string {
  switch (e.kind) {
    case "player":
      return "игрок " + e.id + " x=" + e.pos.x + " ключи=" + e.keys.length;
    case "walker":
      return "ходок " + e.id + " x=" + e.pos.x;
    case "coin":
      return "монета " + e.id + (e.taken ? " взята" : " +" + e.value);
    case "door":
      return "дверь " + e.id + (e.locked ? " заперта" : " открыта");
    case "key":
      return "ключ " + e.id + (e.taken ? " взят" : " лежит");
    default:
      return assertNever(e);
  }
}

step разбирает сущности по kind: игрок упирается в запертую дверь, монету и ключ берёт в радиусе REACH = 8 px, дверь открывает своим ключом.

// src/world.ts — один шаг симуляции
import { assertNever, type Entity, type Player } from "./entities.ts";

export type World = { width: number; tick: number; score: number; entities: Entity[]; log: string[] };

const REACH = 8;

function near(a: Entity, b: Entity): boolean {
  return Math.abs(a.pos.x - b.pos.x) <= REACH && Math.abs(a.pos.y - b.pos.y) <= REACH;
}

function findPlayer(w: World): Player | undefined {
  for (const e of w.entities) {
    if (e.kind === "player") return e;
  }
  return undefined;
}

export function step(w: World): void {
  w.tick += 1;
  const player = findPlayer(w);
  for (const e of w.entities) {
    switch (e.kind) {
      case "player": {
        const blocked = w.entities.some(
          (d) => d.kind === "door" && d.locked && d.pos.x > e.pos.x && d.pos.x - e.pos.x <= e.speed
        );
        if (!blocked) e.pos.x = Math.min(w.width, e.pos.x + e.speed);
        break;
      }
      case "walker":
        e.pos.x += e.dir * e.speed;
        if (e.pos.x <= 0 || e.pos.x >= w.width) e.dir = e.dir === 1 ? -1 : 1;
        break;
      case "coin":
        if (player && !e.taken && near(player, e)) {
          e.taken = true;
          w.score += e.value;
          w.log.push("шаг " + w.tick + ": монета " + e.id + ", счёт " + w.score);
        }
        break;
      case "key":
        if (player && !e.taken && near(player, e)) {
          e.taken = true;
          player.keys.push(e.id);
          w.log.push("шаг " + w.tick + ": ключ " + e.id);
        }
        break;
      case "door":
        if (player && e.locked && e.key !== undefined && player.keys.includes(e.key) && near(player, e)) {
          e.locked = false;
          w.log.push("шаг " + w.tick + ": дверь " + e.id + " открыта ключом " + e.key);
        }
        break;
      default:
        assertNever(e);
    }
  }
}
// src/level.ts — проверка JSON уровня на входе
import { assertNever, type Entity, type EntityKind, type Vec } from "./entities.ts";

export type Level = { name: string; width: number; entities: Entity[] };
export type ParseResult = { ok: true; level: Level } | { ok: false; errors: string[] };

type Obj = Record<string, unknown>;

// Record требует ключ для каждого типа: забытый тип — ошибка TS2741
const KINDS: Record<EntityKind, true> = { player: true, walker: true, coin: true, door: true, key: true };

function isObj(v: unknown): v is Obj {
  return typeof v === "object" && v !== null && !Array.isArray(v);
}

function isKind(v: unknown): v is EntityKind {
  return typeof v === "string" && Object.hasOwn(KINDS, v);
}

function typeName(v: unknown): string {
  if (v === null) return "null";
  if (Array.isArray(v)) return "array";
  return typeof v;
}

export function parseLevel(data: unknown): ParseResult {
  const errors: string[] = [];
  const num = (o: Obj, k: string, path: string): number => {
    const v = o[k];
    if (typeof v === "number" && Number.isFinite(v)) return v;
    errors.push(path + "." + k + ": ожидалось число, получено " + typeName(v));
    return 0;
  };
  const str = (o: Obj, k: string, path: string): string => {
    const v = o[k];
    if (typeof v === "string" && v.length > 0) return v;
    errors.push(path + "." + k + ": ожидалась строка, получено " + typeName(v));
    return "";
  };
  const bool = (o: Obj, k: string, path: string): boolean => {
    const v = o[k];
    if (typeof v === "boolean") return v;
    errors.push(path + "." + k + ": ожидалось true или false, получено " + typeName(v));
    return false;
  };
  const vec = (o: Obj, path: string): Vec => {
    const p = o["pos"];
    if (!isObj(p)) {
      errors.push(path + ".pos: ожидался объект, получено " + typeName(p));
      return { x: 0, y: 0 };
    }
    return { x: num(p, "x", path + ".pos"), y: num(p, "y", path + ".pos") };
  };

  if (!isObj(data)) return { ok: false, errors: ["уровень: ожидался объект"] };
  const name = str(data, "name", "level");
  const width = num(data, "width", "level");
  const raw = data["entities"];
  if (!Array.isArray(raw)) return { ok: false, errors: errors.concat(["level.entities: ожидался массив"]) };

  const entities: Entity[] = [];
  const ids = new Set<string>();
  raw.forEach((item: unknown, i: number) => {
    const path = "entities[" + i + "]";
    if (!isObj(item)) {
      errors.push(path + ": ожидался объект, получено " + typeName(item));
      return;
    }
    const kind = item["kind"];
    if (!isKind(kind)) {
      errors.push(path + ".kind: неизвестный тип " + JSON.stringify(kind));
      return;
    }
    const id = str(item, "id", path);
    if (ids.has(id)) errors.push(path + ".id: повтор " + JSON.stringify(id));
    ids.add(id);
    const pos = vec(item, path);
    switch (kind) {
      case "player":
        entities.push({ kind, id, pos, speed: num(item, "speed", path), keys: [] });
        break;
      case "walker": {
        const dir = item["dir"] === -1 ? -1 : 1;
        entities.push({ kind, id, pos, speed: num(item, "speed", path), dir });
        break;
      }
      case "coin":
        entities.push({ kind, id, pos, value: num(item, "value", path), taken: false });
        break;
      case "key":
        entities.push({ kind, id, pos, taken: false });
        break;
      case "door": {
        const locked = bool(item, "locked", path);
        const key = item["key"];
        if (key === undefined) {
          entities.push({ kind, id, pos, locked });
        } else if (typeof key === "string") {
          entities.push({ kind, id, pos, locked, key });
        } else {
          errors.push(path + ".key: ожидалась строка, получено " + typeName(key));
        }
        break;
      }
      default:
        assertNever(kind);
    }
  });

  if (errors.length > 0) return { ok: false, errors };
  return { ok: true, level: { name, width, entities } };
}

Обвязка загружает уровень через fetch, проверяет parseLevel и рисует по switch с assertNever. Экран загрузки и смена экранов — в статьях про загрузку ресурсов и сцены.

// src/main.ts — обвязка для браузера: загрузка уровня, шаг 1/60 с, отрисовка
import { assertNever, type Entity } from "./entities.ts";
import { parseLevel } from "./level.ts";
import { step, type World } from "./world.ts";

const STEP_MS = 1000 / 60;

function color(e: Entity): string {
  switch (e.kind) {
    case "player":
      return "#3a7bd5";
    case "walker":
      return "#c0392b";
    case "coin":
      return e.taken ? "transparent" : "#f1c40f";
    case "key":
      return e.taken ? "transparent" : "#e67e22";
    case "door":
      return e.locked ? "#7f4f24" : "#b7e4c7";
    default:
      return assertNever(e);
  }
}

function draw(ctx: CanvasRenderingContext2D, w: World): void {
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  for (const e of w.entities) {
    ctx.fillStyle = color(e);
    ctx.fillRect(e.pos.x, 40 + e.pos.y, 12, 12);
  }
}

async function start(): Promise<void> {
  const canvas = document.querySelector("canvas");
  const ctx = canvas?.getContext("2d");
  if (!canvas || !ctx) throw new Error("нет canvas");

  const response = await fetch("level-1.json");
  const result = parseLevel(await response.json());
  if (!result.ok) {
    console.error(result.errors.join("\n"));
    return;
  }
  const level = result.level;
  const world: World = { width: level.width, tick: 0, score: 0, entities: level.entities, log: [] };

  let last = performance.now();
  let acc = 0;
  const frame = (now: number): void => {
    acc += Math.min(now - last, 250);
    last = now;
    while (acc >= STEP_MS) {
      step(world);
      acc -= STEP_MS;
    }
    draw(ctx, world);
    requestAnimationFrame(frame);
  };
  requestAnimationFrame(frame);
}

start().catch((err: unknown) => console.error(err));
// test/run.ts — прогон в Node.js: node test/run.ts
import { readFileSync } from "node:fs";
import { describe } from "../src/entities.ts";
import { parseLevel, type Level } from "../src/level.ts";
import { step, type World } from "../src/world.ts";

function readJson(name: string): unknown {
  const text = readFileSync(new URL("../data/" + name, import.meta.url), "utf8");
  return JSON.parse(text);
}

function play(title: string, level: Level, steps: number): void {
  const w: World = { width: level.width, tick: 0, score: 0, entities: level.entities, log: [] };
  for (let i = 0; i < steps; i++) step(w);
  console.log("== " + title + ": " + level.name + ", шагов " + steps);
  for (const line of w.log) console.log("  " + line);
  console.log("  счёт: " + JSON.stringify(w.score));
  for (const e of w.entities) {
    try {
      console.log("  " + describe(e));
    } catch (err) {
      console.log("  " + e.kind + " " + e.id + ": " + String(err));
    }
  }
}

// 1. Правильный уровень через проверку на входе
const good = parseLevel(readJson("level-1.json"));
if (good.ok) play("проверенный уровень", good.level, 60);
else console.log(good.errors.join("\n"));

// 2. Сломанный уровень без проверки: компилятор молчит
const unchecked = readJson("level-bad.json") as Level;
play("без проверки (as Level)", unchecked, 60);

// 3. Тот же файл через parseLevel
const bad = parseLevel(readJson("level-bad.json"));
console.log("== с проверкой: " + (bad.ok ? "принят" : "отклонён, ошибок " + bad.errors.length));
if (!bad.ok) for (const line of bad.errors) console.log("  " + line);

// 4. Форма верна, но ключа red в уровне нет
const nokey = parseLevel(readJson("level-nokey.json"));
if (nokey.ok) play("форма верна, ключа нет", nokey.level, 60);
else console.log(nokey.errors.join("\n"));
{
  "name": "комната с ключом",
  "width": 200,
  "entities": [
    { "kind": "player", "id": "hero", "pos": { "x": 0, "y": 0 }, "speed": 4 },
    { "kind": "walker", "id": "slime", "pos": { "x": 100, "y": 0 }, "speed": 3, "dir": -1 },
    { "kind": "coin", "id": "c1", "pos": { "x": 40, "y": 0 }, "value": 10 },
    { "kind": "key", "id": "red", "pos": { "x": 60, "y": 0 } },
    { "kind": "coin", "id": "c2", "pos": { "x": 80, "y": 0 }, "value": 5 },
    { "kind": "door", "id": "exit", "pos": { "x": 120, "y": 0 }, "locked": true, "key": "red" },
    { "kind": "coin", "id": "c3", "pos": { "x": 160, "y": 0 }, "value": 25 }
  ]
}
{
  "name": "комната с ключом, правка вручную",
  "width": 200,
  "entities": [
    { "kind": "player", "id": "hero", "pos": { "x": 0, "y": 0 }, "speed": 4 },
    { "kind": "walker", "id": "slime", "pos": { "x": 100, "y": 0 }, "dir": -1 },
    { "kind": "coin", "id": "c1", "pos": { "x": 40, "y": 0 }, "value": "10" },
    { "kind": "coin", "id": "c2", "pos": { "x": 80, "y": 0 }, "value": 5 },
    { "kind": "door", "id": "exit", "pos": { "x": 120, "y": 0 }, "lock": true, "key": "red" },
    { "kind": "coin", "id": "c3", "pos": { "x": 160, "y": 0 }, "value": 25 }
  ]
}

data/level-nokey.json — это level-1.json без ключа red и с именем «комната без ключа».

Файлы ловушек

Каждая ловушка — файл в traps/ со своим tsconfig.

// traps/flags.ts — одна и та же логика при разных флагах
type Enemy = { id: string; hp: number; target?: string };

const enemies: Enemy[] = [
  { id: "bat", hp: 3 },
  { id: "slime", hp: 5, target: "hero" },
];
const waves: string[][] = [["bat"], ["bat", "slime"]];

function findEnemy(id: string) {
  return enemies.find((e) => e.id === id);
}

function damage(e, amount) {
  e.hp -= amount;
}

class Spawner {
  next: string;
  spawn(): string {
    return this.next;
  }
}

const boss = findEnemy("boss");
console.log("hp босса: " + boss.hp);

const third = waves[2];
console.log("третья волна: " + third.length);

const calm: Enemy = { id: "ghost", hp: 1, target: undefined };
damage(calm, 1);
console.log(new Spawner().spawn() + calm.hp);
// traps/spring.ts — в объединение добавили новый тип, а ветку забыли
type Walker = { kind: "walker"; x: number; speed: number };
type Coin = { kind: "coin"; x: number; value: number };
type Spring = { kind: "spring"; x: number; power: number };
type Entity = Walker | Coin | Spring;

function assertNever(x: never): never {
  throw new Error("неизвестный тип сущности: " + JSON.stringify(x));
}

// Вариант А: switch без default — проверка молчит
function updateA(e: Entity): void {
  switch (e.kind) {
    case "walker":
      e.x += e.speed;
      break;
    case "coin":
      break;
  }
}

// Вариант Б: default с assertNever — ошибка на месте забытой ветки
function updateB(e: Entity): void {
  switch (e.kind) {
    case "walker":
      e.x += e.speed;
      break;
    case "coin":
      break;
    default:
      assertNever(e);
  }
}

// Вариант В: функция с результатом — ловит и без assertNever
function points(e: Entity): number {
  switch (e.kind) {
    case "walker":
      return 0;
    case "coin":
      return e.value;
  }
}

const spring: Entity = { kind: "spring", x: 50, power: 12 };
updateA(spring);
console.log("А: пружина x=" + spring.x + ", ошибок нет");
console.log("В: очки " + points(spring));
try {
  updateB(spring);
} catch (err) {
  console.log("Б: " + String(err));
}
// traps/escape.ts — четыре способа обратиться к врагу, которого нет
type Enemy = { id: string; hp: number };
const enemies: Enemy[] = [{ id: "bat", hp: 3 }];

function findEnemy(id: string): Enemy | undefined {
  return enemies.find((e) => e.id === id);
}

function attempt(label: string, read: () => number): void {
  try {
    console.log(label + ": hp " + read());
  } catch (err) {
    console.log(label + ": " + String(err));
  }
}

attempt("1 честно", () => findEnemy("boss").hp);
attempt("2 as Enemy", () => (findEnemy("boss") as Enemy).hp);
attempt("3 оператор !", () => findEnemy("boss")!.hp);
attempt("4 any", () => {
  const raw: any = findEnemy("boss");
  return raw.hp;
});
attempt("5 проверка", () => {
  const boss = findEnemy("boss");
  return boss === undefined ? 0 : boss.hp;
});
// traps/score.ts — ошибка типа, которую транспилятор не заметит
function addScore(score: number, bonus: number): number {
  return score + bonus;
}

const bonusFromUi = "10";
console.log("счёт: " + addScore(5, bonusFromUi));
// traps/reexport/types.ts
export type Enemy = { id: string; hp: number };
export const MAX_HP = 5;
// traps/reexport/index.ts — собираем публичные имена модуля
import { Enemy, MAX_HP } from "./types.ts";
export { Enemy, MAX_HP };
// traps/reexport/main.ts
import { MAX_HP } from "./index.ts";
console.log("MAX_HP = " + MAX_HP);
// traps/enum.ts — синтаксис, который нельзя просто стереть
enum Kind {
  Player,
  Coin,
}
const types = { Player: "player", Coin: "coin" } as const;
type KindName = (typeof types)[keyof typeof types];

const k: KindName = types.Coin;
console.log("enum: " + Kind.Coin + ", объект: " + k);
traps/tsconfig.loose.json
{ "compilerOptions": { "noEmit": true, "strict": false }, "files": ["flags.ts"] }
traps/tsconfig.strict.json
{ "compilerOptions": { "noEmit": true, "strict": true }, "files": ["flags.ts"] }
traps/tsconfig.index.json
{ "extends": "./tsconfig.strict.json", "compilerOptions": { "noUncheckedIndexedAccess": true } }
traps/tsconfig.exact.json
{ "extends": "./tsconfig.index.json", "compilerOptions": { "exactOptionalPropertyTypes": true } }
traps/tsconfig.reexport-iso.json
{ "extends": "./tsconfig.reexport.json", "compilerOptions": { "isolatedModules": true } }

Остальные настройки устроены так же: strict: true, noEmit и свой файл в files; tsconfig.reexport.json добавляет allowImportingTsExtensions, а варианты -iso, -vms и enum-erasable наследуют базовый файл через extends и включают один флаг из названия.

Проверка одним скриптом

check.mjs запускает tsc, esbuild и Node.js на всех файлах; вывод одинаков при каждом запуске на тех же версиях.

// check.mjs — все проверки статьи одним прогоном: node check.mjs
import { spawnSync } from "node:child_process";
import { cpSync, rmSync, mkdirSync, readFileSync, writeFileSync, symlinkSync, statSync } from "node:fs";
import { buildSync, version as esbuildVersion } from "esbuild";

const TSC = "node_modules/typescript/bin/tsc";

function tsc(args, cwd, quiet) {
  const r = spawnSync(process.execPath, [TSC].concat(args), { cwd: cwd || ".", encoding: "utf8" });
  const lines = (r.stdout + r.stderr).split("\n").filter((l) => l.length > 0);
  const codes = [];
  for (const l of lines) {
    const m = l.match(/ error (TS\d+)/);
    if (m) codes.push(m[1]);
  }
  console.log("tsc " + args.join(" ") + " -> ошибок " + codes.length + (codes.length ? " (" + codes.join(", ") + ")" : ""));
  if (!quiet) for (const l of lines) console.log("  " + l);
}

function node(file) {
  const r = spawnSync(process.execPath, [file], { encoding: "utf8" });
  console.log("node " + file + " -> код выхода " + r.status);
  for (const l of r.stdout.split("\n").filter((x) => x.length > 0)) console.log("  " + l);
  const err = r.stderr.split("\n").find((l) => /^\w*Error\b/.test(l));
  if (err) console.log("  " + err);
}

function bundle(entry, outfile) {
  const r = buildSync({ entryPoints: [entry], bundle: true, format: "esm", outfile, logLevel: "silent" });
  console.log("esbuild " + entry + " --bundle -> ошибок " + r.errors.length + ", " + outfile + " " + statSync(outfile).size + " байт");
}

console.log("# 0. Версии");
const v = spawnSync(process.execPath, [TSC, "--version"], { encoding: "utf8" }).stdout.trim();
console.log("tsc: " + v + "; esbuild: " + esbuildVersion + "; node: " + process.version);

console.log("# 1. Флаги строгости: traps/flags.ts");
for (const c of ["loose", "strict", "index", "exact"]) tsc(["-p", "traps/tsconfig." + c + ".json"], ".", c !== "exact");
node("traps/flags.ts");

console.log("# 2. Забытая ветка: traps/spring.ts");
tsc(["-p", "traps/tsconfig.spring.json"]);
node("traps/spring.ts");

console.log("# 3. as, ! и any гасят ошибку: traps/escape.ts");
tsc(["-p", "traps/tsconfig.escape.json"]);
node("traps/escape.ts");

console.log("# 4. Транспилятор не проверяет типы: traps/score.ts");
tsc(["-p", "traps/tsconfig.score.json"]);
mkdirSync("out", { recursive: true });
bundle("traps/score.ts", "out/score.js");
node("out/score.js");
node("traps/score.ts");

console.log("# 5. Реэкспорт типа: traps/reexport");
for (const c of ["reexport", "reexport-iso", "reexport-vms"]) tsc(["-p", "traps/tsconfig." + c + ".json"]);
node("traps/reexport/main.ts");
bundle("traps/reexport/main.ts", "out/reexport.js");
node("out/reexport.js");

console.log("# 6. enum и стирание типов: traps/enum.ts");
for (const c of ["enum", "enum-erasable"]) tsc(["-p", "traps/tsconfig." + c + ".json"]);
node("traps/enum.ts");
bundle("traps/enum.ts", "out/enum.js");
node("out/enum.js");

console.log("# 7. Проект: проверка типов, сборка, прогон");
tsc(["-p", "."]);
bundle("src/main.ts", "out/game.js");
node("test/run.ts");

console.log("# 8. В проект добавили Spring, ветки не дописали");
rmSync("spring-check", { recursive: true, force: true });
mkdirSync("spring-check");
for (const f of ["src", "test", "tsconfig.json", "package.json"]) cpSync(f, "spring-check/" + f, { recursive: true });
symlinkSync("../node_modules", "spring-check/node_modules");
const entFile = "spring-check/src/entities.ts";
writeFileSync(entFile, readFileSync(entFile, "utf8").replace(
  "export type Entity = Player | Walker | Coin | Door | Key;",
  "export type Spring = { kind: \"spring\"; id: string; pos: Vec; power: number };\n" +
  "export type Entity = Player | Walker | Coin | Door | Key | Spring;"
));
tsc(["-p", "."], "spring-check");
rmSync("spring-check", { recursive: true, force: true });
rmSync("out", { recursive: true, force: true });

Вывод прогона (node check.mjs):

# 0. Версии
tsc: Version 7.0.2; esbuild: 0.28.2; node: v24.22.1
# 1. Флаги строгости: traps/flags.ts
tsc -p traps/tsconfig.loose.json -> ошибок 0
tsc -p traps/tsconfig.strict.json -> ошибок 4 (TS7006, TS7006, TS2564, TS18048)
tsc -p traps/tsconfig.index.json -> ошибок 5 (TS7006, TS7006, TS2564, TS18048, TS18048)
tsc -p traps/tsconfig.exact.json -> ошибок 6 (TS7006, TS7006, TS2564, TS18048, TS18048, TS2375)
  traps/flags.ts(14,17): error TS7006: Parameter 'e' implicitly has an 'any' type.
  traps/flags.ts(14,20): error TS7006: Parameter 'amount' implicitly has an 'any' type.
  traps/flags.ts(19,3): error TS2564: Property 'next' has no initializer and is not definitely assigned in the constructor.
  traps/flags.ts(26,28): error TS18048: 'boss' is possibly 'undefined'.
  traps/flags.ts(29,32): error TS18048: 'third' is possibly 'undefined'.
  traps/flags.ts(31,7): error TS2375: Type '{ id: string; hp: number; target: undefined; }' is not assignable to type 'Enemy' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
    Types of property 'target' are incompatible.
      Type 'undefined' is not assignable to type 'string'.
node traps/flags.ts -> код выхода 1
  TypeError: Cannot read properties of undefined (reading 'hp')
# 2. Забытая ветка: traps/spring.ts
tsc -p traps/tsconfig.spring.json -> ошибок 2 (TS2345, TS2366)
  traps/spring.ts(31,19): error TS2345: Argument of type 'Spring' is not assignable to parameter of type 'never'.
  traps/spring.ts(36,29): error TS2366: Function lacks ending return statement and return type does not include 'undefined'.
node traps/spring.ts -> код выхода 0
  А: пружина x=50, ошибок нет
  В: очки undefined
  Б: Error: неизвестный тип сущности: {"kind":"spring","x":50,"power":12}
# 3. as, ! и any гасят ошибку: traps/escape.ts
tsc -p traps/tsconfig.escape.json -> ошибок 1 (TS2532)
  traps/escape.ts(17,27): error TS2532: Object is possibly 'undefined'.
node traps/escape.ts -> код выхода 0
  1 честно: TypeError: Cannot read properties of undefined (reading 'hp')
  2 as Enemy: TypeError: Cannot read properties of undefined (reading 'hp')
  3 оператор !: TypeError: Cannot read properties of undefined (reading 'hp')
  4 any: TypeError: Cannot read properties of undefined (reading 'hp')
  5 проверка: hp 0
# 4. Транспилятор не проверяет типы: traps/score.ts
tsc -p traps/tsconfig.score.json -> ошибок 1 (TS2345)
  traps/score.ts(7,36): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
esbuild traps/score.ts --bundle -> ошибок 0, out/score.js 172 байт
node out/score.js -> код выхода 0
  счёт: 510
node traps/score.ts -> код выхода 0
  счёт: 510
# 5. Реэкспорт типа: traps/reexport
tsc -p traps/tsconfig.reexport.json -> ошибок 0
tsc -p traps/tsconfig.reexport-iso.json -> ошибок 1 (TS1205)
  traps/reexport/index.ts(3,10): error TS1205: Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.
tsc -p traps/tsconfig.reexport-vms.json -> ошибок 2 (TS1484, TS1205)
  traps/reexport/index.ts(2,10): error TS1484: 'Enemy' is a type and must be imported using a type-only import when 'verbatimModuleSyntax' is enabled.
  traps/reexport/index.ts(3,10): error TS1205: Re-exporting a type when 'verbatimModuleSyntax' is enabled requires using 'export type'.
node traps/reexport/main.ts -> код выхода 1
  SyntaxError: The requested module './types.ts' does not provide an export named 'Enemy'
esbuild traps/reexport/main.ts --bundle -> ошибок 0, out/reexport.js 105 байт
node out/reexport.js -> код выхода 0
  MAX_HP = 5
# 6. enum и стирание типов: traps/enum.ts
tsc -p traps/tsconfig.enum.json -> ошибок 0
tsc -p traps/tsconfig.enum-erasable.json -> ошибок 1 (TS1294)
  traps/enum.ts(2,6): error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled.
node traps/enum.ts -> код выхода 1
  SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript enum is not supported in strip-only mode
esbuild traps/enum.ts --bundle -> ошибок 0, out/enum.js 153 байт
node out/enum.js -> код выхода 0
  enum: 1, объект: coin
# 7. Проект: проверка типов, сборка, прогон
tsc -p . -> ошибок 0
esbuild src/main.ts --bundle -> ошибок 0, out/game.js 7704 байт
node test/run.ts -> код выхода 0
  == проверенный уровень: комната с ключом, шагов 60
    шаг 8: монета c1, счёт 10
    шаг 13: ключ red
    шаг 18: монета c2, счёт 15
    шаг 28: дверь exit открыта ключом red
    шаг 38: монета c3, счёт 40
    счёт: 40
    игрок hero x=200 ключи=1
    ходок slime x=76
    монета c1 взята
    ключ red взят
    монета c2 взята
    дверь exit открыта
    монета c3 взята
  == без проверки (as Level): комната с ключом, правка вручную, шагов 60
    шаг 8: монета c1, счёт 010
    шаг 18: монета c2, счёт 0105
    шаг 38: монета c3, счёт 010525
    счёт: "010525"
    player hero: TypeError: Cannot read properties of undefined (reading 'length')
    ходок slime x=NaN
    монета c1 взята
    монета c2 взята
    дверь exit открыта
    монета c3 взята
  == с проверкой: отклонён, ошибок 3
    entities[1].speed: ожидалось число, получено undefined
    entities[2].value: ожидалось число, получено string
    entities[4].locked: ожидалось true или false, получено undefined
  == форма верна, ключа нет: комната без ключа, шагов 60
    шаг 8: монета c1, счёт 10
    шаг 18: монета c2, счёт 15
    счёт: 15
    игрок hero x=116 ключи=0
    ходок slime x=76
    монета c1 взята
    монета c2 взята
    дверь exit заперта
    монета c3 +25
# 8. В проект добавили Spring, ветки не дописали
tsc -p . -> ошибок 5 (TS2345, TS2741, TS2345, TS2345, TS2345)
  src/entities.ts(31,26): error TS2345: Argument of type 'Spring' is not assignable to parameter of type 'never'.
  src/level.ts(10,7): error TS2741: Property 'spring' is missing in type '{ player: true; walker: true; coin: true; door: true; key: true; }' but required in type 'Record<"coin" | "door" | "key" | "player" | "spring" | "walker", true>'.
  src/level.ts(106,21): error TS2345: Argument of type '"spring"' is not assignable to parameter of type 'never'.
  src/main.ts(21,26): error TS2345: Argument of type 'Spring' is not assignable to parameter of type 'never'.
  src/world.ts(56,21): error TS2345: Argument of type 'Spring' is not assignable to parameter of type 'never'.

Что показал прогон

Все шесть ловушек воспроизвелись: (1) один strict поймал 4 ошибки из 6; (2) Spring без ветки в функции void прошёл молча; (3) as, ! и any дали 1 ошибку на 4 падающие строки; (4) esbuild и Node.js выполнили код с TS2345 и посчитали 510; (5) реэкспорт типа без флагов прошёл tsc и уронил Node.js; (6) JSON через as Level дал счёт «010525» и x=NaN, а parseLevel нашёл 3 ошибки. Раздел 8 — ловушка 2 на всём проекте: один новый тип дал 5 ошибок, по одной на каждое место, где перечисляются сущности.

Время проверки и сборки

Проверка tsc на нашем проекте заняла 97–99 мс по медианам, сборка esbuild — 3 мс; время меняется от запуска к запуску, поэтому оно вне детерминированного вывода. timing.mjs (в папке примера) семь раз запускает tsc -p . отдельным процессом и сборку esbuild через JS API из одного процесса Node.js — на нашем проекте и на «большом» с 300 сгенерированными модулями (305 файлов в src). Linux, 8 виртуальных ядер Intel Xeon, 15 ГиБ памяти, Node.js 24.22.1, три запуска 12.11.2026:

ЧтоДиапазон, мсМедианы, мс
малый проект, tsc -p .92–10897, 99, 99
малый проект, esbuild --bundle2–513, 3, 3
большой проект, tsc -p .114–135119, 123, 130
большой проект, esbuild --bundle15–2920, 21, 22

tsc каждый раз стартует новый процесс, поэтому сравнение неравное. Верх диапазона esbuild — первая сборка: в отдельной серии она заняла 47 мс, следующие шесть — 2–4 мс. 300 модулей прибавили tsc 22–31 мс по медианам тех же запусков — на малом проекте почти всё время уходит на старт.

Что не подтвердилось

Три ожидания прогон опроверг, одно мы не проверяли:

  • «esbuild ломается на реэкспорте типа». Нет: с --bundle он собрал ловушку 5, упал только Node.js.
  • «Без never забытую ветку не поймать». Не всегда: функцию с результатом number поймала TS2366, молчит только void.
  • «Проверенный по форме уровень проходим». Нет: level-nokey.json прошёл parseLevel, а игрок застрял у двери.
  • Ускорение TypeScript 7 в 8–12 раз по сравнению с 6.0 (по заметке к выпуску) — не проверяли: TypeScript 6 в прогоне не было.

Практический сценарий: в игру добавили пружину

Задача: добавить пружину, которая подбрасывает игрока, и не пропустить ни одного места, где разбираются сущности.

  1. Добавить тип. В src/entities.ts — Spring = { kind: "spring"; id: string; pos: Vec; power: number } и | Spring в Entity.
  2. Запустить npm run check. В нашем прогоне — 5 ошибок: describe, KINDS и switch в level.ts, color в main.ts, step в world.ts.
  3. Пройти список. Дописать case "spring", в KINDS — spring: true, в parseLevel — проверку power как числа.
  4. Добавить пружину в данные. В level-1.json — объект с "kind": "spring", в level-bad.json — с "power": "12" строкой.
  5. Проверить. npm run check и npm test.

Проверяемый итог: на шаге 2 компилятор сам перечисляет места для правки, на шаге 5 их 0. Мы прошли эти шаги на копии проекта (вне вывода выше): tsc — 0 ошибок, сломанный уровень отклонён, среди ошибок — power строкой. Без assertNever и Record список на шаге 2 был бы пуст.

Когда вам это не подойдёт

Строгий TypeScript окупается, когда типов сущностей больше нескольких и код живёт дольше вечера; вот где он лишний или его мало:

  • Первая игра на выходные. Проще начать на JavaScript и вернуться к типам, когда сущностей станет больше.
  • Сущности из компонентов. Если объект собирается из компонентов (позиция, здоровье, ИИ), а не выбирается из закрытого списка, одно объединение по kind не подходит.
  • Десятки видов данных из сети. Ручной parseLevel разрастается; удобнее схема, из которой выводятся тип и проверка.
  • Плотные циклы по сетке. noUncheckedIndexedAccess добавляет там много проверок; такой код можно обходить через for...of или вынести в отдельный модуль.

Мы разрабатываем J2DRU — браузерный 2D игровой движок, где логика собирается из событий, условий и действий, а проект можно углублять на TypeScript. Движок в разработке и публично пока не открыт, заявку можно оставить на странице раннего доступа (подача заявки не гарантирует приглашение).

Источники (проверено: 12.11.2026, все страницы открываются с HTTP 200): TypeScript — Announcing TypeScript 7.0 (8 июля 2026; компилятор на Go; совместимость с 6.0; значения по умолчанию; ускорение в 8–12 раз — по данным разработчиков); TSConfig Reference (strict и девять проверок его семейства, значение strict по умолчанию — true); TSConfig — noUncheckedIndexedAccess; TSConfig — exactOptionalPropertyTypes; TSConfig — isolatedModules (реэкспорт типа); TSConfig — verbatimModuleSyntax; TSConfig — erasableSyntaxOnly (enum); TSConfig — allowImportingTsExtensions (только с noEmit или emitDeclarationOnly); TypeScript Handbook — Narrowing (дискриминируемые объединения, never, проверка полноты); Node.js v24 — Modules: TypeScript (стирание типов с 23.6.0, стабильно с 24.12.0; без проверки типов и tsconfig.json; enum; расширения .ts); esbuild — Content Types: TypeScript (нет проверки типов, tsc --noEmit параллельно, isolatedModules, отсутствующие экспорты); MDN — JSON.stringify() (поле со значением undefined в объекте пропускается). Тип результата JSON.parse — any — по файлу lib.es5.d.ts из установленного TypeScript 7.0.2. Игра, ловушки, коды ошибок, числа прогона и время — наш пример и прогон в Node.js 24.22.1.

Читайте также:

Частые вопросы

Включён ли strict в TypeScript по умолчанию?

В TypeScript 6.0 и 7.0 — да: по заметке к выпуску 7.0, strict стал значением по умолчанию вместе с module esnext и пустым types. Но strict не включает noUncheckedIndexedAccess и exactOptionalPropertyTypes: в нашем прогоне файл со strict дал 4 ошибки, а с этими двумя флагами — 6.

Почему TypeScript не заметил ошибку в JSON уровня?

Потому что типы существуют только при проверке, а JSON приходит во время исполнения. JSON.parse возвращает any, и запись as Level ничего не проверяет. В нашем прогоне строка вместо числа превратила счёт в «010525», а пропущенная скорость дала координату NaN. Данные проверяют функцией на входе, которая принимает unknown.

Зачем tsc --noEmit, если esbuild и так собирает TypeScript?

esbuild стирает типы и не проверяет их: файл с ошибкой TS2345 он собрал без ошибок, и игра посчитала 5 + «10» как 510. Документация esbuild прямо советует запускать tsc --noEmit параллельно.