Good Code
The good version treats incoming data as unknown until a small runtime check proves it has the expected shape.
Lesson 02
Check unknown values before using them as trusted application data.
type Settings = {
theme: "light" | "dark";
};
function isSettings(value: unknown): value is Settings {
return (
typeof value === "object" &&
value !== null &&
"theme" in value &&
(value.theme === "light" || value.theme === "dark")
);
}
function readSettings(value: unknown): Settings {
// The type guard earns trust before returning Settings.
if (!isSettings(value)) {
return { theme: "light" };
}
return value;
}type Settings = {
theme: "light" | "dark";
};
function readSettings(value: unknown): Settings {
// Double casting skips the runtime proof unknown requires.
return value as any as Settings;
}The good version treats incoming data as unknown until a small runtime check proves it has the expected shape.
The bad version tells TypeScript to trust the value without earning that trust, so invalid data can travel through the app as if it were safe.