ARTICLE - Dev Stack & Tools

TypeScript in Practice: Types, Generics and Project Setup

TypeScript pays off when checking joins the build: narrow external data, preserve concrete types with generics, and match module resolution to the runtime so the compiler can find affected call sites during change.

2026-08-06 TypeScript Official Documentation 39 views
Advertisement

After a JavaScript project moves to TypeScript, heavy use of any or a CI pipeline that bundles without checking types leaves the compiler unable to find affected call sites when an interface changes. The goal is not complex types for their own sake: connect narrowing, generics and an environment-appropriate tsconfig to the development and build workflow. This guide uses small examples to explain setup, verification and the limits of static types.

TypeScript Check and Build Flow TS source Type checking tsc / editor Same input, two paths Transpile or bundle JavaScript Scope: conceptual flow; type checking is not runtime data validation
Figure 1: TypeScript check and build flow (Scope: conceptual flow; type checking is not runtime data validation)

TypeScript is a core topic in frontend building. For the broader build chain, see the frontend toolchain guide; React and Vue projects can also consult the React guide and Vue Composition API guide.

What Type Checking Can—and Cannot—Do

TypeScript checks relationships in source code during development or compilation and can be transpiled to JavaScript by tsc or another tool. Type annotations do not validate HTTP responses, user input or database values at runtime. External data still needs parsing and runtime validation. The type system can expose code that violates a declared contract before release; it cannot guarantee the program has no runtime errors.

Narrow Union Types with a Discriminant

When a value has several possible shapes, a literal field that distinguishes the branches is safer than making every property optional:

type User = { id: string }
type Result<T> =
  | { ok: true; data: T }
  | { ok: false; error: string }

function readResult(result: Result<User>): string {
  if (result.ok) return result.data.id
  return result.error
}

What to verify: in the if (result.ok) branch, the editor narrows result to the success shape; in the other branch, only error is available. Swapping the fields between branches should produce a type error. Validate external JSON at runtime rather than assuming a cast to Result<User> makes the data trustworthy.

Preserve Specific Types with Generic Constraints

Generics let a reusable function preserve the caller's concrete structure. A constraint limits the required shape without needlessly widening the return type:

function findById<T extends { id: string }>(
  items: readonly T[],
  id: string,
): T | undefined {
  return items.find((item) => item.id === id)
}

const found = findById([{ id: "u1", role: "admin" }], "u1")

What to verify: hovering over found preserves the object shape with role: "admin" and includes undefined; changing the constraint to an unrelated field should make the call fail. This pattern helps with reusable data functions but does not runtime-validate an API response.

Configure tsconfig for the Runtime

strict enables a family of checks, including strictNullChecks and noImplicitAny. noUncheckedIndexedAccess is separate and is not enabled just by setting strict. The following configuration is for an application using a modern bundler and requires a TypeScript version that supports moduleResolution: "bundler" (introduced in TypeScript 5.0):

{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "verbatimModuleSyntax": true,
    "noEmit": true
  }
}

What to verify: with this file at the project root, tsc --noEmit checks files selected by the project configuration without emitting JavaScript. For native Node.js module resolution or a published library, choose settings such as NodeNext to match the runtime and consumers rather than copying the bundler configuration.

  • paths affects TypeScript's module lookup; it does not create aliases for a bundler or Node.js. Configure the runtime tool with the same mapping.
  • Set module and moduleResolution for the target environment. The TypeScript documentation gives different guidance for bundler applications and Node.js projects.
  • verbatimModuleSyntax must match the actual emitter's module behavior. It makes type-only imports explicit, such as with import type; it is not a generic “remove all imports” switch.
  • With noUncheckedIndexedAccess, an array or dictionary lookup may include undefined; add a check or a valid default at the call site.

Add Type Checking to Build and CI

Many bundlers transpile and bundle code without running a full TypeScript check. Add a separate check to confirm code against the project's tsconfig:

npx tsc --noEmit

What to verify: exit code 0 means no TypeScript errors were found within this run's configured scope. It does not mean tests passed, external data is valid or the production build is complete. A non-zero exit points to a setting, declaration or call site to investigate. Confirm TypeScript is installed and the current directory uses the intended tsconfig.json.

Project target Starting module settings When they fit
Browser app bundled by a bundler module: "esnext", moduleResolution: "bundler" A tool such as Vite handles runtime bundling
Node.js app run directly module: "nodenext" (resolution follows the module mode) Output runs under Node.js module rules
Library published for external use Check against supported consumers; avoid bundler-only resolution by default Declarations and imports must fit the target runtimes

This table is a decision starting point, not a copy-paste recipe; validate declaration output against the library's intended consumers and release format.

For an existing JavaScript project, first add the check to CI, then tighten settings and add types module by module. Avoid using any to erase errors. A known, isolated issue can be temporarily recorded with a documented @ts-expect-error and a cleanup condition instead of disabling global checks.

Limitations

  • Types constrain development-time code only. Validate network responses, forms, files and database values at runtime.
  • tsc --noEmit depends on tsconfig, declaration files and the selected project scope; error counts are not comparable across projects.
  • Bundler applications, Node.js applications and published libraries have different module-resolution targets. moduleResolution: "bundler" is not suitable for every project that runs directly or publishes for unknown environments.
  • This guide focuses on narrowing, generics and common project settings; it does not cover declaration publishing, decorators, JSX or complex project-reference strategies.

FAQ

How should an older project migrate after strict reports many errors?

Migrate module by module and keep strict enabled. Fix implicit any, nullability and contract problems within a fixed CI scope; a documented @ts-expect-error can temporarily isolate a known issue if an owner and cleanup condition are recorded. Expand the checked scope as the affected code is repaired, and run npx tsc --noEmit consistently in CI.

Which projects should enable noUncheckedIndexedAccess?

No. strict enables a group of checks, while noUncheckedIndexedAccess must be configured separately. It accounts for undefined on indexed reads and is useful when missing keys or out-of-range values need explicit handling. Assess existing code and plan checks around array and dictionary access. Check both array reads and dictionary lookups.

What does tsc --noEmit require before it can run?

Install TypeScript first. Run the command from the directory containing the intended tsconfig.json; tsc --noEmit checks only files selected by that configuration and does not validate runtime JSON. If the config is elsewhere, pass -p path/to/tsconfig.json; confirm its include covers the intended files. Parse network responses, user input and persisted data at the boundary before passing values to typed application code. Run npx tsc --noEmit in CI to repeat the same configured check.

Why can a bundler still fail to resolve an alias from paths?

Not by themselves. paths is used by TypeScript when resolving modules and does not rewrite runtime imports. Configure the bundler, test tool or Node.js loader to use the same alias. tsc --noEmit verifies only the type-side resolution, so run the actual build or tests separately. With Vite, also declare the same mapping under resolve.alias and run a production build.

Related Providers

  • Node.js: align TypeScript module settings with the runtime when checking, testing and building Node.js applications.
  • Vite: coordinate bundler module resolution, transpilation and type checking in a frontend application.
  • Visual Studio Code: surface TypeScript diagnostics in the editor and share workspace settings across a team.

References

Community & Resources

  • TypeScript documentation — The official entry point for the handbook, release notes and configuration options.
  • Narrowing — How control-flow analysis uses typeof checks and discriminants.
  • Generics — Inference, constraints and generic parameters.
  • TypeScript Playground — Paste a minimal example to inspect inference and compiler results.

Original source: TypeScript Official Documentation ↗