Skip to content

Instantly share code, notes, and snippets.

@victor141516
Created April 7, 2025 19:03
Show Gist options
  • Save victor141516/589e4977ad45ba61eac055f0658565d9 to your computer and use it in GitHub Desktop.
Save victor141516/589e4977ad45ba61eac055f0658565d9 to your computer and use it in GitHub Desktop.
/**
* Asserts that a value is of a specific type.
* If the assertion fails, an error is thrown.
*
* @param value The value to type check (used only in type signature)
* @param checker A function that returns true if the value is of the expected type
* @param message Optional custom error message
* @throws Error if the checker returns false
*/
export function assert<T>(
value: unknown,
checker: () => boolean,
message?: string
): asserts value is T {
if (!checker()) {
throw new Error(message || `Type assertion failed: ${String(value)}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment