Sub topic 3
Why `as` Assertions Are Not a Fix
Assume that you know basic TypeScript types, unions, object literals, type inference, and type annotations. You should also understand that TypeScript checks types during compilation, while JavaScript runs later without TypeScript's type information.
A type assertion uses the as keyword to tell TypeScript to treat a value as a particular type:
const value = "hello" as string;The assertion changes what the compiler believes about value. It does not convert the value, check it, or change it at runtime.
Assertions can hide invalid data
Consider data from a file, network request, or JSON.parse. TypeScript cannot know its shape automatically, so the result of JSON.parse is commonly treated as unknown or any.
type User = {
name: string;
age: number;
};
const raw: unknown = JSON.parse('{"name":"Ada"}');
// This compiles, but the object does not contain age.
const user = raw as User;
try {
console.log(user.name);
console.log(user.age.toFixed(0));
} catch (error) {
console.log("Runtime failure:", error instanceof Error ? error.message : error);
}The assertion tells the compiler that raw is a User, even though the actual object has no age property. The compiler therefore allows user.age.toFixed(0). At runtime, user.age is undefined, so calling toFixed fails.
The assertion did not validate the object. It only removed a warning.
Assertions do not convert values
An assertion is also different from a conversion. This assertion does not turn a string into a number:
const text = "42" as unknown as number;
console.log(typeof text); // "string"
console.log(text); // "42"The double assertion through unknown bypasses TypeScript's normal compatibility checks. The runtime value remains a string.
To convert the value, use a runtime operation:
const text = "42";
const numberValue = Number(text);
console.log(typeof numberValue); // "number"
console.log(numberValue + 1); // 43The same distinction matters for object types. Writing raw as User does not add missing properties, rename misspelled properties, or verify nested values.
Why assertions can look attractive
Assertions are short and often make an error disappear:
type Options = {
port: number;
host: string;
};
const options = {
port: 8080,
hots: "localhost",
} as Options;
console.log(options.host);The property is misspelled as hots, but the assertion allows the object to be treated as Options. The compiler does not protect the configuration from this typo. At runtime, options.host is undefined.
A type annotation would catch the problem:
type Options = {
port: number;
host: string;
};
// Error: "hots" is not a known property of Options.
const options: Options = {
port: 8080,
hots: "localhost",
};The annotation checks the object and gives the variable the declared type. The assertion instead tells TypeScript to trust the expression.
Assertions also discard useful precision
Suppose a value has a more specific inferred type than the type you assert:
type Color = "red" | "green" | "blue";
const color = "green" as Color;
// color has the broader type Color, not the single literal type "green".The assertion may be safe here, but it can still hide information. TypeScript can no longer use the fact that this particular value is exactly "green" when that fact matters.
The same problem appears with object properties:
type RGB = [number, number, number];
const palette = {
red: [255, 0, 0],
green: "#00ff00",
} as Record<string, string | RGB>;
// The asserted type says every property may be either a string or an RGB tuple.
function printColor(value: string | RGB): void {
console.log(Array.isArray(value) ? value.join(",") : value.toUpperCase());
}
printColor(palette.green);The assertion gives palette.green the broad type string | RGB, even though the actual property is a string. Code that uses the property must handle both possibilities.
The compiler's trust boundary
This is the working model for an assertion:
An assertion is reasonable when the missing information comes from something you can establish independently. For example, a DOM lookup may be known to return a specific element because the page template guarantees it. Even then, a runtime null check may be safer.
An assertion is risky when it is used to silence an error about external data, configuration, user input, or a failed type design.
What to use instead
When you want to check an expression against a type while preserving its inferred details, use the satisfies operator:
type Color = "red" | "green" | "blue";
type RGB = [number, number, number];
const palette = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
} satisfies Record<Color, string | RGB>;
console.log(palette.green.toUpperCase());
console.log(palette.red.map((channel) => channel * 2));Here, satisfies checks that the object has valid color keys and valid values. It does not replace the expression's specific property types with string | RGB. The next chapter examines this behavior in detail.
Exercise
What does const value = input as User do at runtime, and what should you add if input comes from an untrusted JSON response?
Show answer
The assertion does nothing at runtime. It only changes the compiler's view of the value. Add runtime validation, such as explicit checks or a schema validator, before treating the data as a User.