deno.land / std@0.201.0 / assert / assert_instance_of.ts

assert_instance_of.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
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.import { AssertionError } from "./assertion_error.ts";
// deno-lint-ignore no-explicit-anytype AnyConstructor = new (...args: any[]) => any;type GetConstructorType<T extends AnyConstructor> = T extends // deno-lint-ignore no-explicit-anynew (...args: any) => infer C ? C : never;
/** * Make an assertion that `obj` is an instance of `type`. * If not then throw. */export function assertInstanceOf<T extends AnyConstructor>( actual: unknown, expectedType: T, msg = "",): asserts actual is GetConstructorType<T> { if (actual instanceof expectedType) return;
const msgSuffix = msg ? `: ${msg}` : "."; const expectedTypeStr = expectedType.name;
let actualTypeStr = ""; if (actual === null) { actualTypeStr = "null"; } else if (actual === undefined) { actualTypeStr = "undefined"; } else if (typeof actual === "object") { actualTypeStr = actual.constructor?.name ?? "Object"; } else { actualTypeStr = typeof actual; }
if (expectedTypeStr === actualTypeStr) { msg = `Expected object to be an instance of "${expectedTypeStr}"${msgSuffix}`; } else if (actualTypeStr === "function") { msg = `Expected object to be an instance of "${expectedTypeStr}" but was not an instanced object${msgSuffix}`; } else { msg = `Expected object to be an instance of "${expectedTypeStr}" but was "${actualTypeStr}"${msgSuffix}`; }
throw new AssertionError(msg);}
std

Version Info

Tagged at
a year ago