Sub topic 1
TypeScript `keyof`, `typeof`, and Indexed Access Types
Prerequisites
Assume you know TypeScript interfaces, type aliases, union types, JavaScript objects, and basic generics. This chapter focuses on the boundary between TypeScript's type system and JavaScript's runtime values.
Two worlds: types and values
TypeScript has a type space and a value space. Types describe data during compilation. Values are the objects, strings, and functions that exist when JavaScript runs.
An interface exists only in type space:
interface User {
id: number;
name: string;
}A const exists in value space:
const user = { id: 1, name: "Ada" };You cannot use a type where JavaScript expects a value. You also cannot use most values directly where TypeScript expects a type. Type operators connect the two spaces.
Getting an object type's keys with `keyof`
keyof is a type operator. Given an object type, it produces a union of its property names:
interface User {
id: number;
name: string;
email?: string;
}
type UserKey = keyof User;
// "id" | "name" | "email"The result is a union of string literal types. A value of type UserKey must be one of those names.
Deriving a type from a value with `typeof`
In a type position, typeof reads the type of a value. This differs from JavaScript's runtime typeof, which returns strings such as "string" or "object".
const config = {
host: "localhost",
port: 8080,
};
type Config = typeof config;
// { host: string; port: number }This is useful when the runtime value is the source of truth. Changing the object's properties also changes the derived type.
Keys of a runtime object: `keyof typeof`
Combine the operators to extract keys from a runtime object:
const config = {
host: "localhost",
port: 8080,
};
type ConfigKey = keyof typeof config;
// "host" | "port"
function readConfig(key: ConfigKey): string | number {
return config[key];
}typeof config first creates a type from the value. keyof then extracts that type's keys.
Exercise
What type does keyof typeof settings produce?
Show answer
If settings is { theme: "dark", retries: 3 }, it produces "theme" | "retries".