Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
commit 12f3253892db42e7ce5b9c1ec3da962df0651dc1 Author: skarab42 <skarab@bluewin.ch> Date: Sun Mar 13 07:27:10 2022 +0100 docs: add preprocess type commit 4f81fbab67620358540fad689c96f1c28f87ed6d Author: skarab42 <skarab@bluewin.ch> Date: Sun Mar 13 07:15:26 2022 +0100 test: preprocess type commit 9bc691945f60e60cf642db5fec4335ccbd6f6959 Author: skarab42 <skarab@bluewin.ch> Date: Sun Mar 13 07:15:09 2022 +0100 feat: preprocess type
- Loading branch information
Showing
4 changed files
with
44 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
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
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,13 @@ | ||
import { InferType, Type } from "../types"; | ||
|
||
export function preprocessType< | ||
TFunc extends (input: unknown) => unknown, | ||
TType extends Type<InferType<TType>>, | ||
>(filter: TFunc, type: TType): TType { | ||
return { | ||
...type, | ||
parse(input: unknown) { | ||
return type.parse(filter(input)); | ||
}, | ||
}; | ||
} |
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,18 @@ | ||
import { expect, test } from "vitest"; | ||
import { t } from "../src"; | ||
|
||
test("preprocess() string", () => { | ||
const preprocess = t.preprocess((input) => String(input), t.string()); | ||
expect(preprocess.parse("42")).toBe("42"); | ||
expect(preprocess.parse(42)).toBe("42"); | ||
}); | ||
|
||
test("preprocess() number", () => { | ||
const preprocess = t.preprocess((input) => Number(input), t.number()); | ||
expect(preprocess.parse("42")).toBe(42); | ||
expect(preprocess.parse(42)).toBe(42); | ||
|
||
expect(() => preprocess.parse(undefined)).toThrow( | ||
"expected 'number' got 'NaN'", | ||
); | ||
}); |