From df0723de02e807f4df8161b98a545d99ff0c589e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafa=20G=C3=B3mez?= <rgomezcasas@gmail.com> Date: Wed, 12 Feb 2025 15:35:52 +0100 Subject: [PATCH] feat!: convert date to iso instead of number Since it's a more standard approach --- src/Primitives.ts | 22 +++++++++++++++++----- tests/Primitives.test.ts | 5 +++-- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/Primitives.ts b/src/Primitives.ts index 0a04ea9..07aed5d 100644 --- a/src/Primitives.ts +++ b/src/Primitives.ts @@ -1,4 +1,16 @@ /* eslint-disable @typescript-eslint/no-unsafe-function-type */ +type Year = `${number}${number}${number}${number}`; +type Month = `${number}${number}`; +type Day = `${number}${number}`; +type Hour = `${number}${number}`; +type Minute = `${number}${number}`; +type Second = `${number}${number}`; +type Milliseconds = `${number}${number}${number}`; +type Timezone = "Z" | `${"+" | "-"}${number}${number}:${number}${number}`; + +export type ISODateTime = + `${Year}-${Month}-${Day}T${Hour}:${Minute}:${Second}.${Milliseconds}${Timezone}`; + type Methods<T> = { [P in keyof T]: T[P] extends Function ? P : never; }[keyof T]; @@ -9,16 +21,16 @@ type Properties<T> = Omit<MethodsAndProperties<T>, Methods<T>>; type PrimitiveTypes = string | number | boolean | undefined | null; -type DateToNumber<T> = T extends Date ? number : T; +type DateToISODateTime<T> = T extends Date ? ISODateTime : T; type ValueObjectValue<T> = T extends PrimitiveTypes ? T : T extends Date - ? number + ? ISODateTime : T extends { value: infer U } - ? DateToNumber<U> + ? DateToISODateTime<U> : T extends Array<{ value: infer U }> - ? DateToNumber<U>[] + ? DateToISODateTime<U>[] : T extends Array<infer U> ? Array<ValueObjectValue<U>> : T extends { [K in keyof Properties<T>]: unknown } @@ -26,7 +38,7 @@ type ValueObjectValue<T> = T extends PrimitiveTypes [K in keyof Properties<T>]: ValueObjectValue<Properties<T>[K]>; } : T extends unknown - ? DateToNumber<T> + ? DateToISODateTime<T> : never; export type Primitives<T> = { diff --git a/tests/Primitives.test.ts b/tests/Primitives.test.ts index aee0448..1a8a464 100644 --- a/tests/Primitives.test.ts +++ b/tests/Primitives.test.ts @@ -1,6 +1,7 @@ import { expectTypeOf } from "expect-type"; import { Primitives } from "../src"; +import { ISODateTime } from "../src/Primitives"; import { Course } from "./Course"; import { DeliveryInfo } from "./DeliveryInfo"; import { Learner } from "./Learner"; @@ -70,12 +71,12 @@ describe("Primitives", () => { expectTypeOf<actualPrimitives>().toEqualTypeOf<expectedPrimitives>(); }); - it("should get primitive number type from Date", () => { + it("should get primitive ISO string type from Date", () => { type actualPrimitives = Primitives<Step>; type expectedPrimitives = { readonly name: string; - readonly publishedAt: number; + readonly publishedAt: ISODateTime; }; expectTypeOf<actualPrimitives>().toEqualTypeOf<expectedPrimitives>();