Const Type Parameters Keep Literal Keys

Const type parameters stop inference from widening literals: config.mode stays "strict" instead of string, so keys and values keep their literal types.

TypescriptConfig Management

Code

typescriptsnippet
20 lines
// 普通推断会把属性拓宽成 string;const 类型参数保留字面量
function defineConfig<const T extends Record<string, string | number>>(config: T): T {
  return config;
}

const config = defineConfig({
  host: 'localhost',
  port: 8080,
  mode: 'strict',
});

// config.mode 的类型是字面量 'strict',而不是 string
type Mode = typeof config.mode;
const mode: Mode = 'strict';
console.log('mode:', mode);

// 键名联合同样来自推断
type KnownKeys = keyof typeof config;
const key: KnownKeys = 'port';
console.log('config[' + key + ']:', config[key]);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

mode: strict
config[port]: 8080

What to watch for

The const modifier in function defineConfig<const T extends Record<string, string | number>>(config: T): T changes how inference treats the argument: without it, mode: 'strict' would widen to string and the property type would be useless for assignment checks. With it, typeof config.mode stays the literal 'strict', which is why const mode: Mode = 'strict' compiles and any other string would not.

The constraint keeps the input a flat record of strings and numbers, so the helper accepts config-shaped objects and rejects arbitrary ones. Key names survive the same way: keyof typeof config produces the union of 'host' | 'port' | 'mode' straight from the inferred type, and const key: KnownKeys = 'port' type-checks because port belongs to that union.

The runtime half just prints what the types promised — mode: strict and config[port]: 8080 in the captured output — so the example shows the literal types holding end to end.

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library.