|
1 | | -export interface TransitionAbortedErrorConstructor { |
2 | | - new (message?: string): ITransitionAbortedError; |
3 | | - readonly prototype: ITransitionAbortedError; |
| 1 | +export interface TransitionAbortedError extends Error { |
| 2 | + name: 'TransitionAborted'; |
| 3 | + code: 'TRANSITION_ABORTED'; |
4 | 4 | } |
5 | 5 |
|
6 | | -export interface ITransitionAbortedError extends Error { |
7 | | - constructor: TransitionAbortedErrorConstructor; |
| 6 | +export function isTransitionAborted(maybeError: unknown): maybeError is TransitionAbortedError { |
| 7 | + return ( |
| 8 | + typeof maybeError === 'object' && |
| 9 | + maybeError !== null && |
| 10 | + (maybeError as TransitionAbortedError).code === 'TRANSITION_ABORTED' |
| 11 | + ); |
8 | 12 | } |
9 | 13 |
|
10 | | -const TransitionAbortedError: TransitionAbortedErrorConstructor = (function () { |
11 | | - TransitionAbortedError.prototype = Object.create(Error.prototype); |
12 | | - TransitionAbortedError.prototype.constructor = TransitionAbortedError; |
13 | | - |
14 | | - function TransitionAbortedError(this: ITransitionAbortedError, message?: string) { |
15 | | - let error = Error.call(this, message); |
16 | | - this.name = 'TransitionAborted'; |
17 | | - this.message = message || 'TransitionAborted'; |
| 14 | +interface Abortable<T extends boolean> { |
| 15 | + isAborted: T; |
| 16 | + [key: string]: unknown; |
| 17 | +} |
18 | 18 |
|
19 | | - if (Error.captureStackTrace) { |
20 | | - Error.captureStackTrace(this, TransitionAbortedError); |
21 | | - } else { |
22 | | - this.stack = error.stack; |
23 | | - } |
24 | | - } |
| 19 | +function isAbortable<T extends boolean>(maybeAbortable: unknown): maybeAbortable is Abortable<T> { |
| 20 | + return ( |
| 21 | + typeof maybeAbortable === 'object' && |
| 22 | + maybeAbortable !== null && |
| 23 | + typeof (maybeAbortable as Abortable<T>).isAborted === 'boolean' |
| 24 | + ); |
| 25 | +} |
25 | 26 |
|
26 | | - return TransitionAbortedError as any; |
27 | | -})(); |
| 27 | +export function buildTransitionAborted() { |
| 28 | + let error = new Error('TransitionAborted') as TransitionAbortedError; |
| 29 | + error.name = 'TransitionAborted'; |
| 30 | + error.code = 'TRANSITION_ABORTED'; |
| 31 | + return error; |
| 32 | +} |
28 | 33 |
|
29 | | -export default TransitionAbortedError; |
| 34 | +export function throwIfAborted<T extends boolean>( |
| 35 | + maybe: Abortable<T> |
| 36 | +): T extends true ? never : void; |
| 37 | +export function throwIfAborted(maybe: unknown): void; |
| 38 | +export function throwIfAborted(maybe: unknown | Abortable<boolean>): never | void { |
| 39 | + if (isAbortable(maybe) && maybe.isAborted) { |
| 40 | + throw buildTransitionAborted(); |
| 41 | + } |
| 42 | +} |
0 commit comments