Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add internal utility function assertsUnreachable() #16259

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions cocos/core/data/utils/asserts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,32 @@ export function assertIsTrue (expr: unknown, message?: string): asserts expr {
export function assertsArrayIndex<T> (array: T[], index: number): void {
assertIsTrue(index >= 0 && index < array.length, `Array index ${index} out of bounds: [0, ${array.length})`);
}

/**
* Asserts the caller code's reachability.
*
* @example
* ```ts
* enum Color { RED, GREEN, BLUE }
*
* function toHex(colorThatDefinitelyCannotBeRed: Color): string {
* switch(colorThatDefinitelyCannotBeRed) {
* case Color.GREEN: return '0x00FF00';
* case Color.BLUE: return '0x0000FF';
*
* // Without this:
* // - tsc reports error ts(2366).
* // - eslint reports error about 'consistent-return' and 'default-case'.
* default: return assertsUnreachable();
* }
* }
* ```
*
* @note This function throws in debug mode and returns `undefined` otherwise.
*/
export function assertsUnreachable (): never {
if (DEBUG) {
throw new Error('Here should never be reachable');
}
return undefined as never;
}