keyof and indexed access
When Relay reloads its config, it logs what changed: port: 8080 -> 9090. The helpers behind that
take a key as a string and return any. A typo like get(settings, "prot") compiles, returns
undefined at runtime, and the log line says nothing useful.
The key and the object belong together. The key must be one of the object’s keys, and the result
has that key’s type. Three type operators express this: keyof, indexed access, and a constraint
that links them.
keyof T
Section titled “keyof T”keyof T is the union of the keys of T as string literal types:
interface Settings { readonly port: number readonly queueUrl: string readonly debug: boolean}
type SettingName = keyof Settings // "port" | "queueUrl" | "debug"
const name: SettingName = "port"// @ts-expect-error: '"prot"' is not assignable to type 'keyof Settings'const typo: SettingName = "prot"Indexed access: T[K]
Section titled “Indexed access: T[K]”T[K] is the type of property K of T. It is the type-level version of obj[key]:
interface Job { readonly id: string readonly status: "queued" | "running" | "failed" | "succeeded" readonly queuedAt: number}
type Status = Job["status"] // "queued" | "running" | "failed" | "succeeded"type IdOrTime = Job["id" | "queuedAt"] // string | numbertype AnyValue = Job[keyof Job] // the union of every property type
type Ports = readonly number[]type Port = Ports[number] // number: the element type of an arrayT[number] works for any array or tuple: it is the union of the element types. M2 used
ParseError["_tag"] the same way to get the union of tags.
Const objects: typeof and keyof
Section titled “Const objects: typeof and keyof”A runtime object can give you the type. typeof value in a type position is the type of that
value, and keyof typeof is its keys. You saw this with enum-like objects in lesson 9 of M1:
const STATUS_CODES = { UnknownSource: 404, InvalidJson: 400, InvalidPayload: 422,} as const
type ErrorName = keyof typeof STATUS_CODES // "UnknownSource" | "InvalidJson" | "InvalidPayload"type StatusCode = (typeof STATUS_CODES)[ErrorName] // 404 | 400 | 422Without as const, the values would be widened to number. The table stays the single source of
truth: add a row and both types update.
K extends keyof T
Section titled “K extends keyof T”Now the original problem. A function that takes an object and one of its keys needs two type parameters, and the second one is limited by the first:
function get<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]}
interface Settings { readonly port: number readonly queueUrl: string}declare const settings: Settings
const port = get(settings, "port") // numberconst url = get(settings, "queueUrl") // string// @ts-expect-error: '"prot"' is not assignable to '"port" | "queueUrl"'get(settings, "prot")K extends keyof T limits the key to real keys. T[K] gives the type of that key. Both
parameters appear more than once, so they relate things (lesson 1). When key is the literal
"port", K is "port" and T[K] is number. A looser version, (obj: T, key: keyof T): T[keyof T],
would return number | string for every key.
The same pattern works for lists:
function pluck<T, K extends keyof T>(items: readonly T[], key: K): T[K][] { return items.map((item) => item[key])}
declare const jobs: readonly { readonly id: string; readonly queuedAt: number }[]const times = pluck(jobs, "queuedAt") // number[]Why Object.keys returns string[]
Section titled “Why Object.keys returns string[]”You would expect Object.keys(settings) to give (keyof Settings)[]. It gives string[]:
interface Settings { readonly port: number readonly queueUrl: string}declare const settings: Settings
const keys = Object.keys(settings) // string[]for (const key of keys) { // @ts-expect-error: 'string' can't be used to index type 'Settings' console.log(settings[key])}This follows from structural typing (M1 objects). A value typed Settings may have
more keys than Settings lists:
interface Settings { readonly port: number}const extended = { port: 8080, secret: "x" }const s: Settings = extended // allowed: extra properties are fineObject.keys(s) // ["port", "secret"] at runtime, and the type can't know thatSo (keyof Settings)[] would be a lie. When you know the object has no extra keys, you can write a
helper that keeps the type, and the cost is a guard that checks nothing beyond the key being present:
function typedKeys<T extends object>(obj: T): (keyof T)[] { const isKey = (key: string): key is Extract<keyof T, string> => key in obj return Object.keys(obj).filter(isKey)}typedKeys is as honest as its caller. It never returns a key that isn’t in the object, but with
extra keys it silently hides them. Use it for objects Relay created itself, not for data from the
outside.
keyof of a union
Section titled “keyof of a union”keyof on a union gives the keys they share, because only those are safe on any member. On an
intersection it gives all keys:
interface Started { readonly jobId: string readonly worker: string}interface Failed { readonly jobId: string readonly reason: string}
type Common = keyof (Started | Failed) // "jobId"type All = keyof (Started & Failed) // "jobId" | "worker" | "reason"Exercise
Section titled “Exercise”Relay’s config reload helpers use string keys and any. Tie each key to its object with keyof.
changedKeys needs to return keys, not strings, so the type system can follow them.
keyof Tis the union ofT’s keys.T[K]is the type of propertyK.T[number]is an array’s element type.keyof typeof objturns a const object into a key union, and(typeof obj)[K]into its values.<T, K extends keyof T>(obj: T, key: K): T[K]links a key to its value’s type and rejects typos.Object.keysreturnsstring[]because objects may have extra keys. A typed-keys helper is a promise you make, not one the compiler checks.keyof (A | B)is the shared keys.keyof (A & B)is all of them.
Further reading
Section titled “Further reading”- Handbook: Keyof Type Operator: the
keyofoperator. - Handbook: Indexed Access Types:
T[K]lookups.