-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
isConstructor.ts
34 lines (32 loc) · 876 Bytes
/
isConstructor.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
import type { AnyConstructor } from './AnyConstructor.js'
/**
* Is the subject a constructor function.
*
* @deprecated this is not a failsafe test,
* it will return true for any function that can be called with `new`.
*
* If the subject is an arrow function,
* it can still return true after compilation.
*
* Thus this function is not safe to use.
*/
export function isConstructor(subject: unknown): subject is AnyConstructor {
try {
;new (subject as AnyConstructor)()
} catch (err: any) {
const msg = err?.message as string | undefined
if (msg && msg.indexOf('is not a constructor') >= 0) {
return false
}
}
return true
}
/**
* instanceof type guard for unknown value.
*/
export function isInstanceof<T extends AnyConstructor>(
subject: unknown,
classConstructor: T
): subject is InstanceType<T> {
return subject instanceof classConstructor
}