Sub topic 1
Two worlds: types and values
Overview
Every TypeScript file has two layers. One layer is the JavaScript program that runs. The other is a layer of type descriptions that exists only while you edit and compile. The operators in this tutorial (keyof, typeof in a type position, and T[K]) are tools for moving information between those layers. If you can't tell which layer a piece of code is in, those operators will look arbitrary. Once you can, their rules follow from a single idea.
This chapter builds that mental model. It also covers the error messages you will see when the layers get mixed up.
Prerequisites
This chapter assumes you know the following:
- Basic TypeScript syntax: interfaces, type aliases, and union types.
- JavaScript objects, arrays, and functions.
- The idea of generics (a type parameter such as
T). You don't need to have written complex ones.
You also need a way to run the compiler. Any TypeScript 4.x or 5.x setup works, including the online TypeScript Playground. Examples with a commented // Error line fail to compile on purpose.
Type space and value space
A name in TypeScript can live in type space, in value space, or in both.
- Value space holds things that exist when the program runs: variables, functions, object literals, class constructors. Their contents change as the program executes.
- Type space holds things that exist only for the compiler: interfaces, type aliases, generic parameters, and the annotations you attach to values.
The compiler removes type space completely when it produces JavaScript. This is called type erasure. Consider this file:
interface User {
id: number;
name: string;
}
const user: User = { id: 1, name: "Ada" };
function greet(u: User): string {
return "Hello, " + u.name;
}
console.log(greet(user));After compilation, the JavaScript looks like this:
const user = { id: 1, name: "Ada" };
function greet(u) {
return "Hello, " + u.name;
}
console.log(greet(user));The interface User declaration is gone. So are the : User and : string annotations. Nothing about User exists at runtime, so you cannot inspect it, loop over it, or pass it to a function.
Which space am I in?
You can tell the space from the position of the code. There is no keyword that announces it.
Type space applies in these positions:
- After a colon in an annotation:
let x: Foo - After
asin an assertion:value as Foo - Inside angle brackets:
Array<Foo> - After
extendsorimplements - To the right of
type Name =
Value space applies in these positions:
- To the right of
=in a normal assignment - Function arguments
- Any expression statement
Look at one line with both:
const origin: { x: number; y: number } = { x: 0, y: 0 };The part after the colon, { x: number; y: number }, is a type. The part after =, { x: 0, y: 0 }, is a value. The braces and property names look alike, but they mean different things. The first describes a shape and the second creates an object.
What lives where
Each declaration puts its name into one space or both.
| Declaration | Type space | Value space |
|---|---|---|
| `interface` | Yes | No |
| `type` alias | Yes | No |
| Generic parameter such as `T` | Yes | No |
| `const`, `let`, `var` | No | Yes |
| `function` | No | Yes |
| `class` | Yes (the instance type) | Yes (the constructor) |
| `enum` | Yes (the union of members) | Yes (the enum object) |
Classes and enums are the two declarations that occupy both spaces at once. This is why you can write new Session("a") and also let s: Session:
class Session {
constructor(public id: string) {}
}
const s: Session = new Session("abc"); // type position, then value positionIn : Session, the name means "an instance of Session". In new Session(...), the name means "the constructor function". These are two different things that share a name.
Using a name in the wrong space
Two compiler errors come from mixing spaces. You will meet both often.
The first error uses a type where a value is needed:
interface Point {
x: number;
y: number;
}
// const p = Point;
// Error: 'Point' only refers to a type, but is being used as a value here.An interface has no runtime object. Nothing exists for Point to refer to.
The second error uses a value where a type is needed:
const origin = { x: 0, y: 0 };
// let copy: origin;
// Error: 'origin' refers to a value, but is being used as a type here.
// Did you mean 'typeof origin'?The compiler's suggestion is the fix, and it leads to the next section.
typeof has two meanings
The word typeof appears in both spaces, and it does a different job in each.
In value space, typeof is the JavaScript operator. It runs at runtime and returns a string such as "string", "number", or "object". TypeScript also uses it to narrow types:
function describe(x: string | number): string {
if (typeof x === "string") {
return x.toUpperCase(); // x is string here
}
return x.toFixed(2); // x is number here
}
console.log(describe("hi")); // HI
console.log(describe(3.14159)); // 3.14In type space, typeof is a TypeScript-only operator. It takes a value and returns that value's type. It produces no runtime code. It is the bridge from value space into type space:
const origin = { x: 0, y: 0 };
type Origin = typeof origin; // { x: number; y: number }
const copy: Origin = { x: 5, y: 5 };Now Origin is a type derived from the object. If you add a property to origin, the type updates with it, and you never keep two definitions in sync by hand.
The same keyword is read as a different operator based on position only:
const mode = "dark";
const runtimeCheck = typeof mode; // value space: the string "string"
type ModeType = typeof mode; // type space: the type "dark"The first line yields a string you can print. The second yields a type you can use in annotations. (ModeType is "dark", not string, because a const string keeps its literal type. A later chapter covers this in more detail.)
There is no bridge in the other direction
Value space can't read type space. A function cannot receive User as an argument, because User doesn't exist at runtime. This matters most for keyof, which belongs to type space only:
const config = { host: "localhost", port: 8080 };
const runtimeKeys = Object.keys(config); // value: ["host", "port"], typed string[]
type ConfigKey = keyof typeof config; // type: "host" | "port"These two lines answer different questions. Object.keys gives you an array of strings you can loop over while the program runs. keyof typeof config gives the compiler a union of the exact key names so it can reject typos. Neither replaces the other. The string[] result from Object.keys is deliberately wide, because at runtime an object may carry extra properties beyond its declared type.
If you need keys both as a runtime list and as a type, start from a value and derive the type from it. The as const chapters show how.
Same name in both spaces
Because the spaces are separate, one name can be declared in each. This is legal:
interface Status {
code: number;
label: string;
}
const Status = {
ok: { code: 200, label: "OK" },
notFound: { code: 404, label: "Not Found" },
};
const response: Status = Status.ok;In const response: Status, the name is read in type space and finds the interface. In Status.ok, it is read in value space and finds the constant. The compiler picks the declaration that matches the position.
Use this sparingly. It is common in libraries (a const object plus a type of the same name), but it surprises readers. It also causes confusion with imports, which brings up the next point.
Imports and the type-only marker
When you import a name, it comes in under every space it occupies. If an import is only ever used as a type, the compiler drops it from the emitted JavaScript. With some build setups (isolated module compilers such as Babel or esbuild), the tool can't tell whether a name is a type or a value without the full program. Mark type-only imports explicitly:
import type { User } from "./user";
import { type Role, isRole } from "./roles";import type declares that the name lives in type space only. The compiler errors if you then use it as a value. This also documents your intent to the reader.
Putting the model to work
The rest of the tutorial applies this model, so here is the preview in terms of spaces.
| Operator | Reads from | Produces | Example |
|---|---|---|---|
| `typeof x` (type position) | A value | A type | `typeof config` |
| `keyof T` | A type | A union of key types | `keyof User` |
| `T[K]` | A type and a key type | The type of that property | `User["id"]` |
All three operators work on type space and give back types. Only the first one reaches into value space, and that is why keyof typeof config needs both words. typeof converts the value config into a type, and then keyof reads the keys of that type.
const config = { host: "localhost", port: 8080 };
type Config = typeof config; // value -> type
type ConfigKey = keyof Config; // type -> key union
type PortType = Config["port"]; // type + key -> property type, which is numberWhen you hit an unfamiliar error involving these operators, ask two questions. First: which space is each name in? Second: does the operator I wrote expect that space? Most errors come down to a mismatch there.
Edge cases
- Enums are in both spaces, so
typeofand the plain name differ. Forenum Color { Red, Green }, the typeColoris the union of the membersColor.Red | Color.Green, buttypeof Coloris the type of the enum object itself, an object withRedandGreenproperties. - Classes: instance type versus constructor type. For a class
Session,Sessionin type position is the instance type.typeof Sessionis the constructor type. If you want to accept a class itself as an argument, you annotate it withtypeof Session, notSession. - Functions are values. A function declaration lives in value space, so to describe its type you write
typeof fn. The ReturnType chapter returns to this. - Erased does not mean absent from errors. Types are checked at compile time only. If data arrives from a network call or
JSON.parse, the annotation you give it is a promise and not a check. TypeScript will not validate it for you at runtime.
Summary of the model
- Type space is for the compiler and is erased. Value space is the program that runs.
- Position decides which space a name is read in.
interface,type, and generics are type-only.const,let, andfunctionare value-only.classandenumare both.typeofin a type position turns a value into a type.keyofandT[K]work entirely inside type space.- The two common errors are "only refers to a type, but is being used as a value" and "refers to a value, but is being used as a type".
Exercise
The following code does not compile. Name the error's cause in terms of type space and value space, and give the one-word fix to the annotation. const limits = { min: 0, max: 100 }; let bounds: limits = { min: 1, max: 10 };
Show answer
limits is a variable, so it lives only in value space, but the annotation after the colon expects a type. Write let bounds: typeof limits = { min: 1, max: 10 };. The word to add is typeof.
Exercise
For class Session { constructor(public id: string) {} }, which of these annotations accepts the class itself (for example Session passed as an argument), and which accepts an object created with new Session("a")? The options are Session and typeof Session.
Show answer
typeof Session is the constructor type, so it accepts the class itself. Session in a type position is the instance type, so it accepts an object created with new Session("a"). The class occupies both spaces, and the name means a different thing in each.
Exercise
In the code const kind = typeof value; type Kind = typeof value;, what does each typeof produce, and which one exists in the emitted JavaScript?
Show answer
The first typeof is the JavaScript runtime operator and returns a string such as "string" or "number". It remains in the emitted JavaScript. The second is the type-space operator and returns the type of value. It is erased during compilation and produces no output.