Blog>
Snippets

Type-safe Configuration Access

Demonstrate how to safely access configuration values using TypeScript for enhanced type safety, preventing common configuration-related errors.
interface AppConfig {
    appName: string;
    apiBaseUrl: string;
}

const getAppConfig = (): AppConfig => {
    return {
        appName: 'MyApp',
        apiBaseUrl: process.env.NODE_ENV === 'production' ? 'https://api.myapp.com' : 'http://localhost:3000',
    };
};
This code snippet defines a TypeScript interface named AppConfig to ensure the structure and type of our application configuration. Then, it implements a function getAppConfig which returns the configuration object adhering to the AppConfig structure. This encourages type safety.
const config: AppConfig = getAppConfig();

const getApiBaseUrl = (): string => {
    return config.apiBaseUrl;
};

console.log(getApiBaseUrl());
Here we safely access the API base URL from our configuration using the getApiBaseUrl function. Since the config object is of type AppConfig, TypeScript ensures that we are accessing an existing property of the correct type.