-
Notifications
You must be signed in to change notification settings - Fork 3
/
util.ts
56 lines (46 loc) · 1.86 KB
/
util.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
export function boolean(value: any): value is boolean {
return value === true || value === false;
}
export function string(value: any): value is string {
return typeof value === 'string' || value instanceof String;
}
export function number(value: any): value is number {
return typeof value === 'number' || value instanceof Number;
}
export function error(value: any): value is Error {
return value instanceof Error;
}
// eslint-disable-next-line @typescript-eslint/ban-types
export function func(value: any): value is Function {
return typeof value === 'function';
}
export function array<T>(value: any): value is T[] {
return Array.isArray(value);
}
export function stringArray(value: any): value is string[] {
return array(value) && (<any[]>value).every(elem => string(elem));
}
export function typedArray<T>(value: any, check: (value: any) => boolean): value is T[] {
return Array.isArray(value) && (<any[]>value).every(check);
}
export function thenable<T>(value: any): value is Thenable<T> {
return value && func(value.then);
}
export function asPromise<T>(value: Promise<T>): Promise<T>;
export function asPromise<T>(value: Thenable<T>): Promise<T>;
export function asPromise<T>(value: T): Promise<T>;
export function asPromise(value: any): Promise<any> {
if (value instanceof Promise) {
return value;
} else if (thenable(value)) {
return new Promise((resolve, reject) => {
value.then((resolved) => resolve(resolved), (error) => reject(error));
});
} else {
return Promise.resolve(value);
}
}