Import Attributes Type JSON Modules

Load config as a JSON module with `with { type: 'json' }` so mislabeled specifiers fail at build time instead of becoming runtime surprises.

TypescriptConfig Management

Code

typescriptsnippet
27 lines
// import attributes declare the module type explicitly.
// A wrong or missing type: 'json' is a compile-time error now.
import limits from './rate-limits.json' with { type: 'json' };
import featureFlags from './flags.json' with { type: 'json' };

interface RateLimits {
  anonymous: number;
  authenticated: number;
}

interface Flags {
  betaCheckout: boolean;
}

const checkedLimits: RateLimits = limits;
console.log('anonymous:', checkedLimits.anonymous);

const flags = featureFlags as Flags;
console.log('beta checkout:', flags.betaCheckout);

// Type-only import reads the *inferred* shape of the JSON module for the
// compiler; the runtime build drops it entirely. Attributes are runtime
// syntax, so a type-only import of the same JSON goes without them.
import type limitsShape from './rate-limits.json';

const shape: typeof limitsShape = checkedLimits;
console.log('authenticated:', shape.authenticated);

What the code does

Top-level bindings flags hold the demo state — nothing sits inside a function scope.

What to watch for

  • Runs with what the toolchain already gives you — nothing extra.

Using it

Expect labeled output — anonymous:, beta checkout:, authenticated: — when the file runs.

Key statements

const shape: typeof limitsShape = checkedLimits;
const checkedLimits: RateLimits = limits;
const flags = featureFlags as Flags;

Interactive Tools for This Topic

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. Its state lives in module-level bindings: `flags`.