typescript / intermediate
Snippet
Deep Readonly Immutability with Const Assertions
Const assertions (`as const`) convert object literals and arrays into read-only literal types recursively, preventing modifications to properties and enforcing strict literal values instead of widened types like string or number.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
const appConfig = {endpoint: "https://api.example.com",timeoutMs: 5000,features: ["auth", "logging"]} as const;type AppConfig = typeof appConfig;function connect(config: AppConfig) {console.log(`Connecting to ${config.endpoint}`);}connect(appConfig);
Breakdown
1
const appConfig = { ... } as const;
Applies const assertion to make all properties recursively readonly and typed with exact literal values.
2
type AppConfig = typeof appConfig;
Extracts the exact readonly type representation using TypeScript's `typeof` operator.
3
function connect(config: AppConfig) {
Accepts only objects matching the exact immutable configuration schema.