تمرين إعادة البناء
Safe JSON Decoder
أعد كتابة decoder آمن في TypeScript يستخدم unknown قبل الثقة بالبيانات.
typescript
~16 دقيقة
متوسط
أعد بناء الكود
Rebuild
هذا هو الكود. اكتبه بنفسك.
الكود المرجعي
type DecodeResult<T> =
| { ok: true; value: T }
| { ok: false; error: string };
interface CourseProgress {
course: string;
completedLessons: number;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function decodeCourseProgress(json: string): DecodeResult<CourseProgress> {
let parsed: unknown;
try {
parsed = JSON.parse(json) as unknown;
} catch (error: unknown) {
return { ok: false, error: error instanceof Error ? error.message : "Invalid JSON" };
}
if (!isRecord(parsed)) {
return { ok: false, error: "Expected an object" };
}
if (typeof parsed.course !== "string" || typeof parsed.completedLessons !== "number") {
return { ok: false, error: "Invalid progress shape" };
}
return {
ok: true,
value: {
course: parsed.course,
completedLessons: parsed.completedLessons,
},
};
}
const result = decodeCourseProgress('{"course":"typescript","completedLessons":10}');
console.log(result);اكتب هنا