Why does an if condition discard valid values?
function formatStock(stock: number | null | undefined): string {
if (stock === null || stock === undefined) {
return "Unavailable";
}
return `${stock} items`;
}
console.log(formatStock(0)); // 0 items
console.log(formatStock(null)); // Unavailable
console.log(formatStock(12)); // 12 items
The compiler analyzes conditions, assignments and early exits. typeof distinguishes primitive types, but typeof null is "object". Use Array.isArray() for arrays, including arrays from another JavaScript realm. instanceof checks a constructor relationship and cannot validate JSON data. [1][7][8]
In the example, zero stock is valid. if (!stock) would treat it as missing. After explicit null and undefined checks, the remaining value is a number. The same distinction matters for text fields where an empty string has meaning.
How do I validate API data without as?
interface Product {
id: string;
price: number;
}
function parseProduct(value: unknown): Product {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
throw new TypeError("Expected a product object");
}
if (
!("id" in value) ||
!Object.hasOwn(value, "id") ||
!("price" in value) ||
!Object.hasOwn(value, "price")
) {
throw new TypeError("Missing product fields");
}
const { id, price } = value;
if (
typeof id !== "string" ||
id.trim().length === 0 ||
typeof price !== "number" ||
!Number.isFinite(price) ||
price < 0
) {
throw new TypeError("Invalid product fields");
}
return { id, price };
}
const payload: unknown = JSON.parse('{"id":"p1","price":0}');
const product = parseProduct(payload);
console.log(product); // { id: 'p1', price: 0 }
JSON can contain any structure even if the API documentation promises a model. Receive parsed data as unknown. The in operator helps narrow an object to one with a property, but also considers its prototype. Object.hasOwn() additionally requires an own property. Since TypeScript 4.9, in can narrow objects whose property was not previously declared. [2][6][9]
The product parser rejects arrays, missing fields, blank IDs, non-finite numbers and negative prices while retaining zero. It constructs a fresh object with only allowed fields. For large nested schemas, consider a validation library with consistent error handling; a type alone is not a validator. This example assumes ordinary JSON data, not arbitrary getters or proxies.
Why can a custom is predicate be unsafe?
function isNumber(value: unknown): value is number {
return typeof value === "number";
}
function isValidPrice(value: number): boolean {
return Number.isFinite(value) && value >= 0;
}
function describeValue(value: string | number): string {
if (isNumber(value)) {
return isValidPrice(value) ? `Price: ${value}` : "Invalid price";
}
return value.trim();
}
console.log(describeValue(-5)); // Invalid price
console.log(describeValue(0)); // Price: 0
console.log(describeValue(" pending ")); // pending
The signature value is number tells the compiler that a true result identifies a number and that false can exclude numbers from a relevant union. If the implementation checks both typeof value === "number" and value >= 0, false can also mean a negative number. An explicit predicate is not automatically a proof that this contract holds. [1][3]
Separate type detection from domain validation. isNumber() recognizes every JavaScript number including NaN, while isValidPrice() returns an ordinary boolean. A negative price cannot accidentally reach the text-method branch. For a distinct domain type, prefer a parser to pretending every number meets the constraints.
How do I filter null and undefined without losing zero?
const scores: (number | undefined)[] = [0, undefined, 8, 10];
const availableScores: number[] = scores.filter(
(score) => score !== undefined,
);
function isPresent<T>(value: T): value is NonNullable<T> {
return value !== null && value !== undefined;
}
const labels = ["", null, "Ready", undefined].filter(isPresent);
console.log(availableScores); // [0, 8, 10]
console.log(labels); // ['', 'Ready']
From TypeScript 5.5, a simple narrowing expression can yield an inferred type predicate. The function must have no explicit return annotation, a single return, no parameter mutation, and a boolean expression that refines the parameter in both directions. Thus filter(score => score !== undefined) can produce number[] without a cast. [3]
filter(Boolean) also removes zero, empty strings and other falsy values, and usually does not provide the desired narrowing. The generic isPresent() retains every non-nullish value and works with earlier TypeScript versions supporting NonNullable. Both zero and the empty label survive in the example.
How do I model state without optional fields and casts?
type RequestState =
| { status: "loading" }
| { status: "success"; items: string[] }
| { status: "error"; message: string };
function assertNever(value: never): never {
throw new Error(`Unexpected state: ${JSON.stringify(value)}`);
}
function getStatusMessage(state: RequestState): string {
switch (state.status) {
case "loading":
return "Loading";
case "success":
return `${state.items.length} items`;
case "error":
return state.message;
default:
return assertNever(state);
}
}
console.log(getStatusMessage({ status: "success", items: [] })); // 0 items
console.log(getStatusMessage({ status: "error", message: "Offline" })); // Offline
Instead of one interface with many optional fields, define a union of valid states. The status field is a discriminant. In the success branch the compiler exposes items, and in the error branch it exposes message, without a non-null assertion. [1]
assertNever() enforces exhaustiveness: add cancelled to the union without adding a case, and compilation fails. This protects an internal contract rather than validating external JSON. Network-supplied states must be recognized at the application boundary first.
When should I use asserts rather than a predicate?
function assertString(value: unknown): asserts value is string {
if (typeof value !== "string") {
throw new TypeError("Expected a string");
}
}
function normalizeLabel(value: unknown): string {
assertString(value);
return value.trim();
}
console.log(normalizeLabel(" Ready ")); // Ready
try {
normalizeLabel(42);
} catch (error: unknown) {
console.log(error instanceof TypeError); // true
}
A predicate returns a boolean so the caller can choose how to handle failure. An assertion function with asserts value is string narrows the type after the call returns normally. When the condition fails, it must throw or otherwise never return to the caller. [4]
Assertions fit invariants and situations where further processing makes no sense. The example rejects a number and trims valid text. For form errors, a structured validation result is often more useful, allowing the user to correct input without exceptions controlling the normal flow.
Why does narrowing disappear in a callback?
interface Selection {
id?: string;
}
function createSaveAction(
selection: Selection,
save: (id: string) => void,
): (() => void) | undefined {
const selectedId = selection.id;
if (selectedId === undefined) {
return undefined;
}
return () => {
save(selectedId);
};
}
const selection: Selection = { id: "p1" };
const saveAction = createSaveAction(selection, console.log);
delete selection.id;
saveAction?.(); // p1
A condition on a mutable property cannot guarantee its value when a callback runs later. TypeScript 5.4 preserves some local variable refinements after the last assignment, but this is not a general guarantee for shared objects. [5]
The local const selectedId captures the checked value before the save action is created. Deleting the original property cannot change that captured identifier. If the product should use the latest selection instead, perform the check inside the callback. A snapshot or live read is a product behavior decision, not merely a compiler fix.
