Skip to content

Commit 766196c

Browse files
committed
🧑‍💻(frontend) Add assert utility for type safety and cleaner checks
Introduces an `assert` utility function. This function provides a clean way to throw an error for falsy values, improving code readability and helping with TypeScript type narrowing by ensuring a variable's expected state before proceeding. Signed-off-by: Robin Weber <[email protected]>
1 parent 21eb04f commit 766196c

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,20 @@
1+
/**
2+
* @param ms - The number of milliseconds to wait.
3+
* @description A utility function that returns a promise that resolves after a specified number of milliseconds.
4+
*/
15
export const sleep = (ms: number) =>
26
new Promise((resolve) => setTimeout(resolve, ms));
7+
8+
/**
9+
* @param condition - The condition to check.
10+
* @param msg - The error message to throw if the condition is false.
11+
* @throws {Error} If the condition is false.
12+
* @description Throws an error if the condition is false.
13+
* Important: The `asserts condition` return type informs TypeScript
14+
* that the condition must be true after this call if no error is thrown.
15+
*/
16+
export function assert(condition: unknown, msg?: string): asserts condition {
17+
if (!condition) {
18+
throw new Error(msg || 'Assertion failed: Condition should be truthy.');
19+
}
20+
}

0 commit comments

Comments
 (0)