تمرين إعادة البناء
Typed Config Loader
أعد كتابة محمّل إعدادات TypeScript يتحقق من JSON قبل استخدامه.
typescript
~12 دقيقة
مبتدئ
أعد بناء الكود
Rebuild
هذا هو الكود. اكتبه بنفسك.
الكود المرجعي
// Run with: npx tsx 11-typed-config-loader.ts [path] (requires @types/node).
import * as fs from "node:fs";
interface AppConfig {
port: number;
environment: "development" | "production";
features: string[];
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function parseConfig(value: unknown): AppConfig {
if (!isRecord(value)) {
throw new Error("Config must be an object");
}
if (typeof value.port !== "number") {
throw new Error("Config port must be a number");
}
if (value.environment !== "development" && value.environment !== "production") {
throw new Error("Config environment is invalid");
}
if (!Array.isArray(value.features) || !value.features.every((item) => typeof item === "string")) {
throw new Error("Config features must be strings");
}
return {
port: value.port,
environment: value.environment,
features: value.features,
};
}
function loadConfig(path: string): AppConfig {
if (!fs.existsSync(path)) {
return { port: 3000, environment: "development", features: [] };
}
const raw: unknown = JSON.parse(fs.readFileSync(path, "utf8"));
return parseConfig(raw);
}
const configPath = process.argv[2] ?? "app.config.json";
console.log(loadConfig(configPath));اكتب هنا