diff --git a/src/Primitives.ts b/src/Primitives.ts index e71ee2e..0a04ea9 100644 --- a/src/Primitives.ts +++ b/src/Primitives.ts @@ -7,21 +7,27 @@ type MethodsAndProperties = { [key in keyof T]: T[key] }; type Properties = Omit, Methods>; -type PrimitiveTypes = string | number | boolean | Date | undefined | null; +type PrimitiveTypes = string | number | boolean | undefined | null; + +type DateToNumber = T extends Date ? number : T; type ValueObjectValue = T extends PrimitiveTypes ? T - : T extends { value: infer U } - ? U - : T extends Array<{ value: infer U }> - ? U[] - : T extends Array - ? Array> - : T extends { [K in keyof Properties]: unknown } - ? { [K in keyof Properties]: ValueObjectValue[K]> } - : T extends unknown - ? T - : never; + : T extends Date + ? number + : T extends { value: infer U } + ? DateToNumber + : T extends Array<{ value: infer U }> + ? DateToNumber[] + : T extends Array + ? Array> + : T extends { [K in keyof Properties]: unknown } + ? { + [K in keyof Properties]: ValueObjectValue[K]>; + } + : T extends unknown + ? DateToNumber + : never; export type Primitives = { [key in keyof Properties]: ValueObjectValue; diff --git a/tests/Primitives.test.ts b/tests/Primitives.test.ts index d8c7ad8..aee0448 100644 --- a/tests/Primitives.test.ts +++ b/tests/Primitives.test.ts @@ -6,6 +6,7 @@ import { DeliveryInfo } from "./DeliveryInfo"; import { Learner } from "./Learner"; import { Metadata } from "./Metadata"; import { Product } from "./Product"; +import { Step } from "./Step"; import { User } from "./User"; import { Video } from "./Video"; @@ -63,7 +64,18 @@ describe("Primitives", () => { type expectedPrimitives = { readonly active: boolean; - readonly createdAt: Date; + readonly name: string; + }; + + expectTypeOf().toEqualTypeOf(); + }); + + it("should get primitive number type from Date", () => { + type actualPrimitives = Primitives; + + type expectedPrimitives = { + readonly name: string; + readonly publishedAt: number; }; expectTypeOf().toEqualTypeOf(); diff --git a/tests/Product.ts b/tests/Product.ts index 6bdc3d5..07fccd7 100644 --- a/tests/Product.ts +++ b/tests/Product.ts @@ -3,13 +3,13 @@ import { Primitives } from "../src"; export class Product { constructor( public readonly active: boolean, - public readonly createdAt: Date, + public readonly name: string, ) {} toPrimitives(): Primitives { return { active: this.active, - createdAt: this.createdAt, + name: this.name, }; } } diff --git a/tests/Step.ts b/tests/Step.ts new file mode 100644 index 0000000..bf4e752 --- /dev/null +++ b/tests/Step.ts @@ -0,0 +1,15 @@ +import { Primitives } from "../src"; + +export class Step { + constructor( + public readonly name: string, + public readonly publishedAt: Date, + ) {} + + toPrimitives(): Primitives { + return { + name: this.name, + publishedAt: this.publishedAt.getTime(), + }; + } +}