Complete worked example
typescript
type Role = { id: string; title: string; country: "US" | "UA" };
function parseRole(value: unknown): Role | undefined {
if (typeof value !== "object" || value === null || !("id" in value) || typeof value.id !== "string"
|| !("title" in value) || typeof value.title !== "string" || !("country" in value)
|| (value.country !== "US" && value.country !== "UA")) return undefined;
return { id: value.id, title: value.title, country: value.country };
}- Reasoning
- Each returned Role is constructed only after the runtime checks justify all required fields.