import { Err, Result } from "../result"; import { RuntimeType, runtimeTypeOf } from "../issues/shared"; import { OpaqueType } from "../type"; export type InstanceOfIssue = { readonly kind: "instance-of"; readonly expectedClass: string | undefined; readonly subject: RuntimeType; }; export type Constructor = Function & { prototype: T } export class InstanceOf extends OpaqueType { readonly klass: Constructor; constructor(klass: Constructor) { super(); this.klass = klass; } check(val: any): Result { if(val instanceof this.klass) return val as Result; return new Err({ kind: "instance-of", expectedClass: this.klass.name || undefined, subject: runtimeTypeOf(val), }); } } export function instanceOf(klass: Constructor): InstanceOf { return new InstanceOf(klass); }