0Pricing
TypeScript Academy · Lesson

Type-Safe Service Tokens

Use typed tokens to avoid runtime resolution errors.

Type-Safe Service Tokens is a free TypeScript Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The String Token Problem

String tokens like "Logger" are easy to typo and carry no type information. The container cannot tell you that get("Loggr") is wrong, and the resolved type is often any.

Symbols as Tokens

Using symbols instead of strings gives each token a unique identity that cannot collide with another by accident. A central registry keeps them organized.

const TYPES = {
  Logger: Symbol.for("Logger"),
  Mailer: Symbol.for("Mailer"),
} as const;

Mapping Tokens to Types

The deeper goal is associating each token with the type it resolves to, so the container returns the correct type instead of any. We build a typed token wrapper.

interface Token<T> {
  readonly id: symbol;
  readonly _type?: T; // phantom type marker
}

Creating Typed Tokens

A helper produces a token that remembers its type in a phantom field. The field never holds a value; it only carries type information for the compiler.

function token<T>(name: string): Token<T> {
  return { id: Symbol.for(name) };
}
const LoggerToken = token<Logger>("Logger");

A Typed Container Interface

We type the container so get infers the resolved type from the token. No casts, no any.

interface TypedContainer {
  get<T>(t: Token<T>): T;
  bind<T>(t: Token<T>, impl: () => T): void;
}

Binding with Inferred Types

When you bind, the factory's return type must match the token's type. Mismatches are caught at compile time.

declare const c: TypedContainer;
c.bind(LoggerToken, () => new ConsoleLogger());
// ConsoleLogger must satisfy Logger or this errors.

Resolving with Full Types

Now get returns exactly the token's type. Autocomplete and type checking work on the result with no manual annotation.

const logger = c.get(LoggerToken); // type: Logger
logger.log("typed resolution");

Avoiding Lookup Mistakes

Because tokens are typed values, a typo references an undefined variable (a compile error) rather than a silent wrong string. The whole class of string-key bugs disappears.

// c.get(LogerToken) -> compile error: LogerToken is not defined

InversifyJS Equivalent

Inversify supports symbol tokens too, and community helpers add typed wrappers. The principle is identical: bind a typed token to an implementation and resolve with the right type.

import { Container } from "inversify";
const TYPES = { Logger: Symbol.for("Logger") };
// container.bind<Logger>(TYPES.Logger).to(ConsoleLogger)

A Token Registry

Centralizing tokens in one module gives a single source of truth, making them easy to discover, refactor, and keep consistent across the codebase.

export const TOKENS = {
  Logger: token<Logger>("Logger"),
  Mailer: token<Mailer>("Mailer"),
};

Benefits Summary

Typed tokens give unique identity (symbols), compile-time safety (mismatches rejected), correct resolved types (no any), and typo protection (undefined variable errors).

Quick Check

Quick check on this lesson.

Recap

Type-safe service tokens wrap a unique symbol with a phantom type, mapping each token to the type it resolves to. get returns the precise type, binding enforces matching implementations, and typos become compile errors instead of silent string-lookup bugs.

Frequently asked questions

Is the “Type-Safe Service Tokens” lesson free?

Yes — the full text of “Type-Safe Service Tokens” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Type-Safe Service Tokens”?

Use typed tokens to avoid runtime resolution errors. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start TypeScript Academy?

No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Type-Safe Service Tokens” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this TypeScript Academy lesson?

Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Inversion of Control Basics
  2. Constructor Injection
  3. DI Containers with InversifyJS
  4. Type-Safe Service Tokens
← Back to TypeScript Academy