2023-07-13 07:04:30 +00:00
|
|
|
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
|
|
|
|
import { AssertionError } from "./assertion_error.ts";
|
|
|
|
|
2023-12-06 17:13:38 +00:00
|
|
|
/** Any constructor */
|
2023-07-13 07:04:30 +00:00
|
|
|
// deno-lint-ignore no-explicit-any
|
2023-12-06 17:13:38 +00:00
|
|
|
export type AnyConstructor = new (...args: any[]) => any;
|
|
|
|
/** Gets constructor type */
|
|
|
|
export type GetConstructorType<T extends AnyConstructor> = T extends // deno-lint-ignore no-explicit-any
|
2023-07-13 07:04:30 +00:00
|
|
|
new (...args: any) => infer C ? C
|
|
|
|
: never;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Make an assertion that `obj` is an instance of `type`.
|
|
|
|
* If not then throw.
|
2023-12-06 17:13:38 +00:00
|
|
|
*
|
|
|
|
* @example
|
|
|
|
* ```ts
|
|
|
|
* import { assertInstanceOf } from "https://deno.land/std@$STD_VERSION/assert/assert_instance_of.ts";
|
|
|
|
*
|
|
|
|
* assertInstanceOf(new Date(), Date); // Doesn't throw
|
|
|
|
* assertInstanceOf(new Date(), Number); // Throws
|
|
|
|
* ```
|
2023-07-13 07:04:30 +00:00
|
|
|
*/
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2023-08-25 09:04:43 +00:00
|
|
|
if (expectedTypeStr === actualTypeStr) {
|
2023-07-13 07:04:30 +00:00
|
|
|
msg =
|
|
|
|
`Expected object to be an instance of "${expectedTypeStr}"${msgSuffix}`;
|
2023-08-25 09:04:43 +00:00
|
|
|
} else if (actualTypeStr === "function") {
|
2023-07-13 07:04:30 +00:00
|
|
|
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);
|
|
|
|
}
|