-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathutil.ts
52 lines (44 loc) · 1.62 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
import {VariantModule, Property} from './variant';
/**
* Useful in generating friendly types. Intersections are rendered as the type of the intersection, not as A & B.
*/
export type Identity<T> = T extends object ? {} & {
[P in keyof T]: T[P]
} : T;
export const identityFunc = <T>(x = {} as T) => x as T extends unknown ? {} : T ;
export type Func = (...args: any[]) => any;
export interface FuncObject {
[key: string]: Func
}
/**
* Extract the data type from a function, whether it returns the
* object directly or does so with a promise.
*/
export type GetDataType<T extends VariantModule<K>, K extends string = 'type'> = {
[P in keyof T]: ReturnType<T[P]> extends PromiseLike<infer R>
? R extends Property<K, string> ? R : never
: ReturnType<T[P]>
}
/**
* Given a union of types all of which meet the contract {[K]: string}
* extract the type that is specifically {[K]: TType}
*/
export type ExtractOfUnion<T, TType extends string, K extends string = 'type'> = T extends Property<K, TType> ? T : never;
/**
* Utility function to create a K:V from a list of strings
*
* Taken from: https://basarat.gitbook.io/typescript/type-system/literal-types#string-based-enums
* */
export function strEnum<T extends string>(o: Array<T>): {[K in T]: K} {
return o.reduce((res, key) => {
res[key] = key;
return res;
}, Object.create(null));
}
/**
* Determine whether or not a variable is a promise.
* @param x
*/
export function isPromise<T>(x: T | PromiseLike<T>): x is PromiseLike<T> {
return x != undefined && typeof x === 'object' && 'then' in x && typeof x.then === 'function';
}