Skip to content

Commit

Permalink
Prioritize toJSON
Browse files Browse the repository at this point in the history
Co-authored-by: Nicholas Rakoto <[email protected]>
  • Loading branch information
pcattori and nrako committed Oct 10, 2023
1 parent 629eca2 commit 7084a1e
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions packages/remix-server-runtime/jsonify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ export type Jsonify<T> =
// any
IsAny<T> extends true ? any :

// toJSON
T extends { toJSON(): infer U } ? (U extends JsonValue ? U : unknown) :

// primitives
T extends JsonPrimitive ? T :
T extends String ? string :
Expand All @@ -28,9 +31,6 @@ export type Jsonify<T> =
// Not JSON serializable
T extends NotJson ? never :

// toJSON
T extends { toJSON(): infer U } ? (U extends JsonValue ? U : unknown) :

// tuple & array
T extends [] ? [] :
T extends readonly [infer F, ...infer R] ? [NeverToNull<Jsonify<F>>, ...Jsonify<R>] :
Expand Down Expand Up @@ -148,6 +148,8 @@ type _tests = [
Expect<Equal<Jsonify<Date>, string>>,
Expect<Equal<Jsonify<{ toJSON(): undefined }>, unknown>>,
Expect<Equal<Jsonify<{ toJSON(): Date }>, unknown>>,
Expect<Equal<Jsonify<BooleanWithToJson>, string>>,


// tuple & array
Expect<Equal<Jsonify<[]>, []>>,
Expand Down Expand Up @@ -224,6 +226,7 @@ class MyClass {
}
}

// real-world example: `InvoiceLineItem` from `stripe`
type Recursive = {
a: Date;
recur?: Recursive;
Expand All @@ -233,6 +236,11 @@ expectType<{ a: string; recur?: Jsonify<Recursive> }>(
recursive.recur!.recur!.recur!
);

// real-world example: `Temporal` from `@js-temporal/polyfill`
interface BooleanWithToJson extends Boolean {
toJSON(): string;
}

// utils ------------------------------------------------------------

type Pretty<T> = { [K in keyof T]: T[K] };
Expand Down

0 comments on commit 7084a1e

Please sign in to comment.