From ec841a2cf3f5f05aed8a35e04381c28e570f684d Mon Sep 17 00:00:00 2001 From: shrinktofit Date: Thu, 14 Sep 2023 18:53:24 +0800 Subject: [PATCH] Add internal utility function assertsUnreachable() --- cocos/core/data/utils/asserts.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/cocos/core/data/utils/asserts.ts b/cocos/core/data/utils/asserts.ts index 8a878e7c1f2..9e387e5ce1d 100644 --- a/cocos/core/data/utils/asserts.ts +++ b/cocos/core/data/utils/asserts.ts @@ -55,3 +55,32 @@ export function assertIsTrue (expr: unknown, message?: string): asserts expr { export function assertsArrayIndex (array: T[], index: number): void { assertIsTrue(index >= 0 && index < array.length, `Array index ${index} out of bounds: [0, ${array.length})`); } + +/** + * Asserts this function should never be called. + * + * @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; +}