类型安全的配置系统
00:00
构建类型安全的应用配置
1. 配置类型定义
interface AppConfig {
api: {
baseURL: string;
timeout: number;
retries: number;
};
features: {
darkMode: boolean;
analytics: boolean;
notifications: boolean;
};
version: string;
}
type ConfigPath = `api.${string}` | `features.${string}` | 'version';
2. 类型安全的配置访问
type DeepGet<T, P extends string> = P extends `${infer K}.${infer Rest}`
? K extends keyof T
? DeepGet<T[K], Rest>
: never
: P extends keyof T
? T[P]
: never;
class ConfigManager<T> {
constructor(private config: T) {}
get<P extends string>(path: P): DeepGet<T, P> {
return path.split('.').reduce((obj: any, key) => obj?.[key], this.config);
}
set<P extends string>(path: P, value: DeepGet<T, P>): void {
const keys = path.split('.');
const last = keys.pop()!;
const target = keys.reduce((obj: any, key) => obj[key], this.config);
target[last] = value;
}
}
const config = new ConfigManager<AppConfig>({
api: { baseURL: 'https://api.example.com', timeout: 5000, retries: 3 },
features: { darkMode: true, analytics: false, notifications: true },
version: '1.0.0',
});
config.get('api.baseURL'); // string
config.get('features.darkMode'); // boolean