Skip to content

Commit

Permalink
perf: infer cleanDate result type from schema
Browse files Browse the repository at this point in the history
  • Loading branch information
IlyaSemenov committed Jan 5, 2023
1 parent ea3e368 commit 0c4170e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
15 changes: 13 additions & 2 deletions packages/data-cleaner/src/clean/date.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { SchemaError } from "../errors/SchemaError"
import { ValidationError } from "../errors/ValidationError"
import { Cleaner } from "../types"
import { getMessage } from "../utils"
import { setSchema } from "./any"
import { cleanString, StringSchema } from "./string"
Expand All @@ -11,11 +12,21 @@ export interface DateSchema<T>
*
* `format: null` - return valid value as is
*
* `format: "iso"` - return ISO-formatted date
* `format: "iso"` - return ISO-formatted date-time
*/
format?: null | "iso"
}

// FIXME: type result as having schema
export function cleanDate<T = Date, V = any>(
schema?: DateSchema<T> & { format?: undefined }
): Cleaner<T, V>

// FIXME: type result as having schema
export function cleanDate<T = string, V = any>(
schema?: DateSchema<T> & { format: "iso" | null }
): Cleaner<T, V>

export function cleanDate<T = Date | string, V = any>(
schema: DateSchema<T> = {}
) {
Expand All @@ -38,7 +49,7 @@ export function cleanDate<T = Date | string, V = any>(
clean(value, context) {
let res: any = value
if (res) {
const date = new Date(res as string)
const date = new Date(res)
if (isNaN(date.getTime())) {
throw new ValidationError(
getMessage(context, "invalid", "Invalid value.")
Expand Down
11 changes: 11 additions & 0 deletions packages/data-cleaner/test-d/date.test-d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { cleanDate } from "data-cleaner"
import { expectType } from "tsd"

expectType<Date>(await cleanDate()(""))

expectType<string>(await cleanDate({ format: "iso" })(""))

expectType<string>(await cleanDate({ format: null })(""))

expectType<boolean>(await cleanDate<boolean>()(""))
expectType<boolean>(await cleanDate<boolean>({ format: "iso" })(""))

0 comments on commit 0c4170e

Please sign in to comment.