Indexed Access Types Extract Field Shapes
Pull field types along object paths with indexed access types, so renamed config fields keep their derived types in sync without hand-written duplicates.
Code
interface RetryPolicy {
maxAttempts: number;
backoffMs: number;
}
interface DatabaseConfig {
host: string;
port: number;
retry: RetryPolicy;
}
interface AppConfig {
env: 'dev' | 'prod';
database: DatabaseConfig;
mirrors: string[];
}
// 索引访问类型沿路径取出字段类型:路径结构改动时这些派生类型自动跟随
type DbHost = AppConfig['database']['host'];
type Retry = AppConfig['database']['retry'];
type RetryMs = AppConfig['database']['retry']['backoffMs'];
// 数组/元组用 [number] 取元素类型
type Mirror = AppConfig['mirrors'][number];
const config = {
env: 'dev',
database: {
host: 'db.internal',
port: 5432,
retry: { maxAttempts: 5, backoffMs: 250 },
},
mirrors: ['eu-1', 'us-2'],
} satisfies AppConfig;
const host: DbHost = config.database.host;
const retry: Retry = config.database.retry;
const firstMirror: Mirror = config.mirrors[0];
console.log('target:', `${host}:${config.database.port}`);
console.log('retry:', retry.maxAttempts, 'attempts,', retry.backoffMs, 'ms backoff');
console.log('first mirror:', firstMirror);Output
Captured from a sandboxed run of this snippet in the build pipeline.
target: db.internal:5432
retry: 5 attempts, 250 ms backoff
first mirror: eu-1Types along a path
AppConfig[‘database’][‘host’] extracts string straight from the config shape; RetryPolicy arrives via AppConfig[‘database’][‘retry’], and the nested backoffMs is one more index away. Renaming or restructuring config updates every derived type automatically.
Element types of arrays
AppConfig[‘mirrors’][number] yields the element type (string) — the indexed-access form works on tuples and arrays alike.
satisfies keeps the shape honest
The config literal carries satisfies AppConfig, so its structure is checked without widening the literal’s own types; host, retry, and firstMirror then annotate cleanly from the derived aliases.
Interactive Tools for This Topic
FAQ
- Why derive types with indexed access instead of writing aliases by hand?
- The derived type stays glued to the real config shape; renaming or moving fields updates the alias automatically, while a hand-written duplicate drifts silently.
- What does satisfies AppConfig add to the literal?
- It validates the literal against the interface without widening its inferred types, so the object keeps its narrowest shape for later annotation.
Report a problem with this exampleOpens a pre-filled issue on GitHub.