Skip to content

Commit 555f001

Browse files
committed
feat(utils): add getType, expand tryCatch return type
1 parent f0f4ce8 commit 555f001

File tree

3 files changed

+57
-4
lines changed

3 files changed

+57
-4
lines changed

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@ export * from './promise.js';
55
export * from './string.js';
66
export * from './types.js';
77
export * from './url.js';
8+
export * from './utils.js';

src/promise.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,12 @@ export async function settled<T>(
1717
return first;
1818
}
1919

20-
export type Success<T> = {
20+
export type Success<T> = [T, null] & {
2121
data: T;
2222
error: null;
2323
};
2424

25-
export type Failure<E> = {
25+
export type Failure<E> = [null, E] & {
2626
data: null;
2727
error: E;
2828
};
@@ -34,8 +34,8 @@ export async function tryCatch<T, E = Error>(
3434
): Promise<Result<T, E>> {
3535
try {
3636
const data = await promise;
37-
return { data, error: null };
37+
return Object.assign([data, null], { data, error: null }) as Result<T, E>;
3838
} catch (error) {
39-
return { data: null, error: error as E };
39+
return Object.assign([null, error], { data: null, error }) as Result<T, E>;
4040
}
4141
}

src/utils.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
export function getType<T extends keyof TypeMap>(
2+
value: unknown,
3+
type: T,
4+
): value is TypeMap[T] {
5+
const s = Object.prototype.toString.call(value);
6+
return s.slice(8, -1).toLowerCase() === type;
7+
}
8+
9+
type TypeMap = {
10+
string: string;
11+
number: number;
12+
bigint: bigint;
13+
boolean: boolean;
14+
symbol: symbol;
15+
undefined: undefined;
16+
null: null;
17+
object: object;
18+
function: Function;
19+
array: any[];
20+
date: Date;
21+
regexp: RegExp;
22+
error: Error;
23+
map: Map<any, any>;
24+
weakmap: WeakMap<object, any>;
25+
set: Set<any>;
26+
weakset: WeakSet<object>;
27+
promise: Promise<any>;
28+
arraybuffer: ArrayBuffer;
29+
dataview: DataView;
30+
int8array: Int8Array;
31+
uint8array: Uint8Array;
32+
uint8clampedarray: Uint8ClampedArray;
33+
int16array: Int16Array;
34+
uint16array: Uint16Array;
35+
int32array: Int32Array;
36+
uint32array: Uint32Array;
37+
float32array: Float32Array;
38+
float64array: Float64Array;
39+
bigint64array: BigInt64Array;
40+
biguint64array: BigUint64Array;
41+
url: URL;
42+
urlsearchparams: URLSearchParams;
43+
blob: Blob;
44+
file: File;
45+
formdata: FormData;
46+
headers: Headers;
47+
request: Request;
48+
response: Response;
49+
readablestream: ReadableStream<any>;
50+
writablestream: WritableStream<any>;
51+
transformstream: TransformStream<any, any>;
52+
};

0 commit comments

Comments
 (0)