Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 96 ยท TypeScript in Practice

TypeScript with Vue, Angular and Express

See how TypeScript works in Express, Vue and Angular - typed route handlers and params, defineProps and defineEmits, Angular dependency injection, and project templates.

Every major JavaScript framework now treats TypeScript as a first-class language. Angular has been written in TypeScript from the start, Vue 3 was rewritten in it, and Express, the most widely used Node.js server framework, has detailed community types. But each one uses TypeScript a little differently, and knowing where the types come from makes you productive in any of them.

This lesson tours three frameworks: Express on the server, then Vue and Angular in the browser. For each one you'll see what TypeScript adds, the typing patterns you'll write every day, and the type-level technique behind it, as a runnable example.

Our editor has no npm packages, so Express, Vue and Angular code is shown read-only. The runnable examples rebuild the key typing ideas in plain TypeScript, and the server examples use Node's built-in node:http module on 127.0.0.1, which works inside a single run.

Express

Express itself is written in JavaScript; its types come from the @types/express package:

Terminal
npm install express
npm install --save-dev typescript @types/express @types/node tsx

Typing route handlers

A handler receives a Request and a Response. Both are generic, so you can describe the route's parameters, response body, request body and query string:

TypeScript
import express, { type Request, type Response } from 'express';

interface User {
  id: number;
  name: string;
}

interface CreateUserBody {
  name: string;
}

const app = express();
app.use(express.json());

//                      Request<Params,           ResBody, ReqBody>
app.get('/users/:id', (req: Request<{ id: string }>, res: Response<User | { error: string }>) => {
  const id = Number(req.params.id); // params are always strings
  const user = findUser(id);
  if (!user) {
    res.status(404).json({ error: 'not found' });
    return;
  }
  res.json(user); // checked against Response<User | { error: string }>
});

app.post('/users', (req: Request<{}, User, CreateUserBody>, res: Response<User>) => {
  const user = createUser(req.body.name); // req.body is CreateUserBody
  res.status(201).json(user);
});

app.listen(3000);

Two things deserve attention:

  • Route parameters are inferred from the path. For an inline handler, @types/express reads the string '/users/:id' and types req.params as { id: string } automatically, using template literal types.
  • req.body is not validated. Typing it as CreateUserBody is a promise, exactly like annotating JSON.parse (see typing APIs). Validate the body with a schema before you trust it.

The parameter inference is a neat trick, and you can build it yourself:

TypeScript Extracting route parameters from a path type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
42 hello-world
{ userId: '1', postId: '2' } {} null

RouteParams is a recursive conditional type: it peels off one :param at a time with infer and collects the names into a mapped type. The as cast inside match() is the one place where runtime code and type meet; the type system can't follow a regular expression.

A typed handler, end to end

Let's put that into a small working server. This isn't Express, but a dozen lines on top of node:http that copy its typing idea: the path decides the type of params, so every handler gets exactly the parameters its route has. The server listens on 127.0.0.1, and the same program sends requests to it with fetch:

TypeScript A tiny typed router on node:http

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
200 /books/1 { id: 1, title: 'Dune' }
404 /books/9 { error: 'no book 9' }
200 /authors/ada/books/1843 { author: 'ada', year: 1843 }
404 /nothing { error: 'no route' }

Inside the handlers, destructuring ({ id }) and ({ author, year }) is fully typed. And if you make a mistake, the compiler catches it before the server ever starts:

TypeScript Using a parameter the path does not have (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The program doesn't run. The errors:

TEXT
main.ts(12,53): error TS2339: Property 'id' does not exist on type '{ orderId: string; }'.
main.ts(13,53): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

The second error is a reminder that URL parameters are always strings: convert them with Number() and check for NaN.

Extending the Request type

Middleware often attaches data to the request, such as the signed-in user. Add the property to Express's Request interface with declaration merging (see declaration files):

TypeScript
// src/types/express.d.ts
import type { User } from '../models/user';

declare global {
  namespace Express {
    interface Request {
      user?: User;
    }
  }
}

export {};
TypeScript
// Any handler can now read req.user, typed as User | undefined
app.get('/me', (req, res) => {
  if (!req.user) {
    res.status(401).end();
    return;
  }
  res.json({ name: req.user.name });
});

Make user optional: routes that run without the authentication middleware really don't have it. Express 5 also forwards errors from async handlers to your error middleware automatically, which is typed as (err: unknown, req, res, next) => void (four parameters). Other Node frameworks such as Fastify, Hono and NestJS go further and infer request and response types from schemas or decorators.

Vue

Vue 3 is written in TypeScript, and its <script setup lang="ts"> syntax infers almost everything. The key macros are defineProps and defineEmits, which take type arguments:

VUE
<script setup lang="ts">
import { ref, computed } from 'vue';

interface Todo {
  id: number;
  title: string;
  done: boolean;
}

// Props from a type; destructuring with defaults works in Vue 3.5+
const { todos, filter = 'all' } = defineProps<{
  todos: Todo[];
  filter?: 'all' | 'open' | 'done';
}>();

// Events: name -> tuple of argument types
const emit = defineEmits<{
  toggle: [id: number];
  rename: [id: number, title: string];
}>();

const editingId = ref<number | null>(null);   // Ref<number | null>

const visible = computed(() =>                 // ComputedRef<Todo[]>
  todos.filter((t) => filter === 'all' || (filter === 'done') === t.done),
);

function finishEdit(todo: Todo, title: string) {
  emit('rename', todo.id, title);  // checked: (id: number, title: string)
  editingId.value = null;
}
</script>

<template>
  <li v-for="todo in visible" :key="todo.id" @click="emit('toggle', todo.id)">
    {{ todo.title }}
  </li>
</template>
  • defineProps<T>() turns a type into runtime prop declarations at compile time, so you write the type only once.
  • ref<T>(), computed() and reactive() infer their types; pass a type argument when the initial value is null.
  • The tsc command doesn't understand .vue files. Vue projects run vue-tsc, a wrapper that type-checks templates too (a misspelled prop in the template is an error), and editors use the Vue (Volar) extension.

The defineEmits type is an event map where each value is a tuple of arguments. Here's how a typed emit function is built from such a map:

TypeScript A typed emit function from an event map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
toggle #3
rename #3 to "Buy oat milk"
(no listener for clearDone)

TodoEvents is a type alias rather than an interface on purpose: type aliases of object literals are assignable to Record<string, unknown[]>, while interfaces are not, because an interface could be extended later by declaration merging (see index signatures). The rest parameter ...args: Events[K] is the core trick: because Events[K] is a tuple, it becomes an exact argument list for each event name. Uncomment the last two lines to see the errors. The type-safe event emitter project develops this into a full library.

Angular

Angular projects are TypeScript by default; the CLI generates a strict configuration. Angular's compiler (ngc) runs on top of TypeScript and also type-checks templates when strictTemplates is on.

TypeScript
import { Component, Injectable, inject, input, output, computed, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';

export interface Product {
  id: number;
  name: string;
  price: number;
}

@Injectable({ providedIn: 'root' })
export class ProductService {
  private http = inject(HttpClient);

  list() {
    return this.http.get<Product[]>('/api/products'); // Observable<Product[]>
  }
}

@Component({
  selector: 'app-product-card',
  template: `
    <h3>{{ product().name }}</h3>
    <p>{{ priceLabel() }}</p>
    <button (click)="addToCart.emit(product().id)">Add</button>
  `,
})
export class ProductCardComponent {
  product = input.required<Product>();   // a typed, required input signal
  currency = input('EUR');               // InputSignal<string>, inferred
  addToCart = output<number>();          // emits a number

  priceLabel = computed(() => `${this.product().price.toFixed(2)} ${this.currency()}`);
  quantity = signal(1);                  // WritableSignal<number>
}

What TypeScript gives you here:

  • Decorators such as @Component and @Injectable attach metadata to classes. Angular has long used TypeScript's legacy experimentalDecorators mode, not the standard decorators covered in Decorators; the Angular compiler handles them for you.
  • Signals (input(), output(), signal(), computed()) are generic functions, so types flow from initial values or type arguments, and templates are checked against them.
  • http.get<T>() works like the unchecked getJson<T> from typing APIs: T is a promise about the server, not a check.
  • Dependency injection is typed by tokens. A class is its own token; for other values you create an InjectionToken<T>, and inject(token) returns T.

That last idea, a token object that carries a type, is worth understanding, because many libraries use it. Here's a tiny DI container with the same typing:

TypeScript Typed injection tokens, Angular-style

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
[log] api=https://api.example.com retries=3
[log] dark mode: true
true
No provider for MISSING

The declare private readonly _type: T line is a type-only property: it makes InjectionToken<AppConfig> and InjectionToken<number> different types (otherwise both would be structurally identical, see type compatibility), and declare means no JavaScript is emitted for it. provide(APP_CONFIG, 42) would now be a compile error.

Starting a project

Every framework has an official template with TypeScript already configured. Prefer these over hand-written setups; they keep tsconfig.json, linting and build tools in sync.

Framework Command Type checking
React (Vite) npm create vite@latest app -- --template react-ts tsc -b
Vue npm create vue@latest (choose TypeScript) vue-tsc --build
Angular npx @angular/cli new app ng build (strict by default)
Svelte npx sv create app (choose TypeScript) svelte-check
Next.js npx create-next-app@latest next build
Express npm init -y, then install express, @types/express, typescript, tsx tsc --noEmit
JSON
{
  "scripts": {
    "dev": "tsx watch src/server.ts",
    "typecheck": "tsc --noEmit",
    "build": "tsc",
    "start": "node dist/server.js"
  }
}

A pattern you'll see everywhere: the dev server strips types for speed and doesn't report type errors, so a separate typecheck script (run in the editor, in CI and before commits) does the real checking. The tooling lesson covers linting, testing and builds.

Typed API errors in Express

Back to the server. A typical Express app starts with each handler building its own error responses: res.status(404).json({ error: 'not found' }) here, res.status(400).send('bad input') there. After a few dozen routes, clients receive five different error shapes, and nobody is sure which status a "duplicate email" gets. The fix is to make errors values with types: handlers throw errors from a small class hierarchy, and one error middleware turns any thrown value into a consistent, typed response.

The plan has three parts:

  • An abstract base class (see Inheritance and Abstract Classes) that forces every API error to declare its HTTP status and a stable machine-readable code.
  • Subclasses for the cases your API really has: not found, validation failed, conflict, unauthorized. Extra data, such as the list of invalid fields, lives on the subclass.
  • A handler that takes unknown, because anything can be thrown (see Error Handling). It narrows with instanceof: known API errors become their status and body, and everything else becomes a 500 with a generic message, so internal details like stack traces never reach the client.

In Express, that last part is an error-handling middleware: a function with four parameters, registered after all routes. The types come from @types/express:

TypeScript
import express, { type ErrorRequestHandler, type RequestHandler } from 'express';

const errorHandler: ErrorRequestHandler = (err: unknown, req, res, next) => {
  if (res.headersSent) {
    next(err); // too late to send JSON; let Express close the connection
    return;
  }
  const { status, body } = toErrorResponse(err); // the function from the example below
  res.status(status).json(body);
};

const getUser: RequestHandler<{ id: string }> = async (req, res) => {
  const user = await db.findUser(req.params.id);
  if (!user) {
    throw new NotFoundError('User', req.params.id); // Express 5 forwards async errors
  }
  res.json(user);
};

const app = express();
app.get('/users/:id', getUser);
app.use(errorHandler); // last, after every route

ErrorRequestHandler types the error parameter as any; annotating it as unknown (which the type accepts) forces you to narrow before you touch it. Express 5 sends rejected promises from async handlers to the error middleware automatically. In Express 4 you had to call next(error) yourself or wrap handlers. The same pattern works in our editor on top of node:http: the routes only throw, and a single toErrorResponse decides what the client sees:

TypeScript An error hierarchy with one error handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
200 /users?id=ada {"id":"ada","name":"Ada Lovelace"}
404 /users?id=bob {"error":{"code":"not_found","message":"User bob does not exist"}}
400 /signup?name=a {"error":{"code":"invalid_request","message":"2 invalid field(s)","issues":[{"field":"name","message":"at least 2 characters"},{"field":"email","message":"required"}]}}
409 /signup?name=ada&email=x {"error":{"code":"conflict","message":"User ada already exists"}}
  [log] unexpected: Expected property name or '}' in JSON at position 1 (line 1 column 2)
500 /crash {"error":{"code":"internal","message":"Something went wrong"}}
404 /admin {"error":{"code":"not_found","message":"Route /admin does not exist"}}

Every failure has the same { error: { code, message } } shape, the validation error adds its issues, and the JSON bug in /crash is logged on the server but hidden from the client. A few details carry the design:

  • abstract readonly status: number means a subclass that forgets its status doesn't compile: TypeScript reports that the non-abstract class doesn't implement the inherited abstract member.
  • readonly status = 404 in a subclass is a property initializer; because it's readonly, its type is the literal 404, which still satisfies the base class's number.
  • override details() is checked against the base method (with noImplicitOverride, the override keyword becomes required).
  • ConflictError declares no constructor, so it inherits Error's (message?: string) one.

A string code works, but a union of known codes is better: clients can switch over it, and the mapping from code to status can live in one table that the compiler keeps complete. as const satisfies (see The satisfies Operator) checks that every status is one you allow while keeping the exact keys for the ErrorCode union:

TypeScript Codes and statuses that cannot drift apart

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
409 conflict Email already registered
That already exists.

Add a new code to errorStatus and the switch in userMessage stops compiling until you handle it, because the function no longer returns a string on every path. If you share ErrorCode and the error body type with the front end (for example from a package both sides import), the typed API client can turn these responses into a typed Result without guessing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In an Express handler for /users/:id, what is the type of req.params.id?

    URL parameters are always strings. @types/express infers { id: string } from the path, so convert with Number() when you need a number.
  2. 2. You type an Express handler as Request<{}, User, CreateUserBody>. What does that guarantee about req.body at runtime?

    The type argument only tells the compiler what to assume. Validate the body (for example with a schema) before trusting it.
  3. 3. In Vue, what does defineEmits<{ rename: [id: number, title: string] }>() give you?

    Each event maps to a tuple of argument types, so emit('rename', 1, 'x') compiles and emit('rename', 1) does not. vue-tsc checks this in templates too.
  4. 4. Which tool type-checks .vue single-file components?

    Plain tsc cannot read .vue files. vue-tsc wraps the TypeScript compiler and also checks template expressions.
  5. 5. What does inject(APP_CONFIG) return when APP_CONFIG = new InjectionToken<AppConfig>("APP_CONFIG")?

    The token carries its type as a type parameter, and inject is generic, so the return type is AppConfig.

Summary

  • Express types come from @types/express. Request<Params, ResBody, ReqBody, Query> and Response<T> describe a route; params are inferred from the path and are always strings.
  • Typing req.body doesn't validate it: check request bodies at runtime. Add properties like req.user with declare global and interface merging.
  • Vue's defineProps<T>() and defineEmits<T>() turn types into component contracts; event maps use tuples for arguments. Check .vue files with vue-tsc.
  • Angular is TypeScript-first: decorators, typed signals (input, output, signal), and dependency injection with InjectionToken<T>.
  • The techniques behind these APIs (template literal types, mapped types, tuple rest parameters, phantom type parameters) are the ones you learned in this course.
  • Start from official templates, and pair a fast type-stripping dev server with a separate tsc --noEmit (or vue-tsc) check.

Next: Tooling: Linting, Testing and Building