Implementing Type-Safe Configurations with TypeScript
Exhibit how to define a configuration schema using TypeScript interfaces to ensure the type safety of application configurations with TanStack Config.
import { defineConfig } from '@tanstack/config';
Imports the defineConfig function from '@tanstack/config' to be used for creating a type-safe configuration.
// Define the configuration schema using TypeScript interface
interface AppConfig {
apiBaseUrl: string;
logLevel: 'debug' | 'info' | 'warn' | 'error';
}
Defines a TypeScript interface 'AppConfig' to describe the structure and types of the application's configuration.
const appConfig = defineConfig<AppConfig>({
apiBaseUrl: 'https://api.example.com',
logLevel: 'debug',
});
Uses the defineConfig function to create a configuration object 'appConfig' with type-checking enforced by the 'AppConfig' interface.
console.log(appConfig.apiBaseUrl); // 'https://api.example.com'
console.log(appConfig.logLevel); // 'debug'
Demonstrates accessing the configuration values with TypeScript ensuring the types are correct according to the AppConfig interface.