TypeScript Course
TypeScript
/
Intermediate

Path Aliases

Definition

A feature configured in `tsconfig.json` that allows you to define custom module resolution paths. It replaces long, messy relative paths (`../../../components/Button`) with clean, absolute aliases (`@/components/Button`).

Explain Like I'm New

Imagine you are deep in a basement room of a giant house. To get to the attic, you have to go up stairs, up stairs, up stairs (`../../../`). Path Aliases are a magical teleporter. You just say `@/attic`, and you instantly import the file, no matter how deep in the basement you are.

Real World Example

Standardizing imports in a Next.js application so that every component import starts cleanly with `@/components/...`.

Common Use Cases

  • •Large codebases
  • •Refactoring (moving a file doesn't break its relative imports)

Interactive Example

// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/components/*": ["src/components/*"],
      "@/utils/*": ["src/utils/*"]
    }
  }
}

// IN YOUR CODE:

// BAD: Fragile relative imports
// import { Button } from "../../../../components/Button";

// GOOD: Clean, unbreakable path alias
// import { Button } from "@/components/Button";

Interview Questions

basic

  • What two properties in `tsconfig` are required to setup path aliases?

intermediate

  • Does TypeScript actually change the paths in the compiled JavaScript output?

advanced

  • Why do path aliases often fail at runtime in Node.js apps?

Flash Cards

Question

What two properties are required?

Click to reveal answer
Answer

You MUST set `"baseUrl"` (usually to `"."` or `"./src"`), and then configure the `"paths"` mapping object.

Question

Why do they fail at runtime in Node.js?

Click to reveal answer
Answer

TypeScript ONLY uses Path Aliases to resolve Types during compilation. It DOES NOT rewrite the paths in the generated `.js` files! Node.js will crash saying 'Cannot find module @/components'. You must use a tool like `tsc-alias`, `tsconfig-paths`, or a bundler (Webpack/Vite) to physically rewrite the paths for runtime.