-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(type): add validator for value type
- Loading branch information
1 parent
9c5309a
commit 262f1d5
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
// Copyright 2023-latest Tomoki Miyauchi. All rights reserved. MIT license. | ||
// This module is browser compatible. | ||
|
||
import { Assert, 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 { | ||
bigint: bigint; | ||
boolean: boolean; | ||
// deno-lint-ignore ban-types | ||
function: Function; | ||
number: number; | ||
// deno-lint-ignore ban-types | ||
object: object | null; | ||
string: string; | ||
symbol: symbol; | ||
undefined: undefined; | ||
} | ||
|
||
export class TypeValidator<T extends Type> | ||
extends AssertiveScalarValidator<unknown, TypeMap[T]> { | ||
declare [Assert.symbol]: TypeMap[T]; | ||
constructor(public of: T) { | ||
super(); | ||
super.expect(message); | ||
} | ||
|
||
override is(input: unknown): input is TypeMap[T] { | ||
// deno-lint-ignore valid-typeof | ||
return typeof input === this.of; | ||
} | ||
|
||
toString(): string { | ||
return `type of ${this.of}`; | ||
} | ||
} | ||
|
||
export function message(this: Display, { input }: { input: unknown }): string { | ||
return format(error.should_be, this, typeof input); | ||
} |