Skip to content

Commit

Permalink
feat(type): add type of null and check "object" type is null or not
Browse files Browse the repository at this point in the history
  • Loading branch information
TomokiMiyauci committed May 22, 2023
1 parent b231f30 commit 77020b4
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions validators/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ import { type Display } from "../types.ts";
import { AssertiveScalarValidator, format } from "../utils.ts";
import error from "./error.json" assert { type: "json" };

export type Type = keyof TypeMap;

export interface TypeMap {
interface LegacyTypeMap {
bigint: bigint;
boolean: boolean;
// deno-lint-ignore ban-types
Expand All @@ -20,6 +18,14 @@ export interface TypeMap {
undefined: undefined;
}

export interface TypeMap extends LegacyTypeMap {
// deno-lint-ignore ban-types
object: object;
null: null;
}

export type Type = keyof TypeMap;

export class TypeValidator<T extends Type>
extends AssertiveScalarValidator<unknown, TypeMap[T]> {
constructor(public of: T) {
Expand All @@ -28,15 +34,23 @@ export class TypeValidator<T extends Type>
}

override is(input: unknown): input is TypeMap[T] {
// deno-lint-ignore valid-typeof
return typeof input === this.of;
return typeOf(input) === this.of;
}

toString(): string {
return `type of ${this.of}`;
}
}

/** Strict {@link typeof} operation. */
export function typeOf(input: unknown): Type {
const of = typeof input;

if (of === "object" && input === null) return "null";

return of;
}

export function message(this: Display, { input }: { input: unknown }): string {
return format(error.should_be_but, this, typeof input);
}

0 comments on commit 77020b4

Please sign in to comment.