0
0
Typescriptprogramming~5 mins

Strict configuration objects in Typescript

Choose your learning style9 modes available
Introduction

Strict configuration objects help catch mistakes early by making sure only allowed settings are used.

When you want to make sure a function only accepts specific options.
When you want to avoid typos in configuration keys.
When you want to get helpful errors while coding instead of bugs later.
When you want to clearly document what settings are allowed.
When you want to prevent extra or unknown properties in objects.
Syntax
Typescript
function setup(config: { optionA: string; optionB: number }): void {
  // use config.optionA and config.optionB
}

Define the exact shape of the config object using an inline type or an interface.

TypeScript will check that only the specified keys are present.

Examples
This function only accepts an object with debug and maxRetries keys.
Typescript
function configure(settings: { debug: boolean; maxRetries: number }) {
  console.log(settings.debug, settings.maxRetries);
}
Using an interface to define the config shape makes the code cleaner and reusable.
Typescript
interface Config {
  url: string;
  timeout: number;
}

function connect(config: Config) {
  console.log(`Connecting to ${config.url} with timeout ${config.timeout}`);
}
Passing a strict config object ensures only allowed options are used.
Typescript
function start(options: { verbose: boolean }) {
  console.log(options.verbose ? 'Verbose mode on' : 'Verbose mode off');
}

start({ verbose: true });
Sample Program

This program defines a strict config object for server settings and prints the server address.

Typescript
interface ServerConfig {
  host: string;
  port: number;
}

function startServer(config: ServerConfig) {
  console.log(`Server running at http://${config.host}:${config.port}`);
}

startServer({ host: 'localhost', port: 8080 });
OutputSuccess
Important Notes

If you pass extra keys not defined in the config type, TypeScript will show an error.

Strict config objects help prevent bugs caused by misspelled or unexpected properties.

Summary

Strict configuration objects define exactly what settings are allowed.

They help catch errors early by checking object keys and types.

Use interfaces or inline types to create strict configs in TypeScript.