Essential assertion utilities and type safety helpers for runtime validation and exhaustiveness checking in Fluid Framework applications.
Browser-friendly assertion function that throws an error when the condition is false. Provides type narrowing through TypeScript's assertion signatures.
/**
* Asserts that a condition is true, throwing an error if it's false
* @param condition - The condition to test
* @param message - Optional error message (string or number)
* @throws Error when condition is false
*/
function assert(condition: any, message?: string | number): asserts condition;Usage Examples:
import { assert } from "@fluidframework/common-utils";
// Basic assertion
const value: unknown = "hello";
assert(typeof value === "string", "Value must be a string");
// TypeScript now knows value is a string
// Assertion with numeric error code
assert(items.length > 0, 404);
// Nullability checks
const maybeUser: User | null = getUser();
assert(maybeUser !== null, "User not found");
// TypeScript now knows maybeUser is User, not nullCompile-time assertion function for exhaustiveness checking in TypeScript switch statements and conditional branches.
/**
* Compile-time assertion for never type, ensures exhaustiveness in switch statements
* @param x - Value that should be of type never
* @throws Error if called at runtime (indicates missing case)
* @returns never (function never returns)
*/
function unreachableCase(x: never): never;Usage Examples:
import { unreachableCase } from "@fluidframework/common-utils";
type Status = "pending" | "completed" | "failed";
function handleStatus(status: Status): string {
switch (status) {
case "pending":
return "Processing...";
case "completed":
return "Done!";
case "failed":
return "Error occurred";
default:
// TypeScript ensures all cases are handled
return unreachableCase(status);
}
}
// If you add a new status to the union type:
type Status = "pending" | "completed" | "failed" | "cancelled";
// TypeScript will now show an error until you add the "cancelled" case
// because unreachableCase() expects a never type but receives "cancelled"Both assertion functions throw Error objects when conditions are not met:
assert() throws when the condition is falsyunreachableCase() throws when called at runtime (which indicates a missing case in your exhaustiveness check)The error messages are designed to be helpful during development and debugging.