Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: simplified types for useLoaderData, useActionData, useFetcher, SerializeFrom #6449

Merged
merged 1 commit into from
May 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions .changeset/lemon-beers-fetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
"@remix-run/server-runtime": minor
"@remix-run/react": minor
---

Force Typescript to simplify type produced by `Serialize`.

As a result, the following types and functions have simplified return types:
- SerializeFrom
- useLoaderData
- useActionData
- useFetcher

```ts
type Data = { hello: string; when: Date }

// BEFORE
type Unsimplified = SerializeFrom<Data>
// ^? SerializeObject<UndefinedToOptional<{ hello: string; when: Date }>>

// AFTER
type Simplified = SerializeFrom<Data>
// ^? { hello: string; when: string }
```
8 changes: 6 additions & 2 deletions packages/remix-server-runtime/serialize.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import type { AppData } from "./data";
import type { TypedDeferredData, TypedResponse } from "./responses";

// force Typescript to simplify the type
type Pretty<T> = { [K in keyof T]: T[K] } & {};

type JsonPrimitive =
| string
| number
Expand All @@ -18,7 +21,7 @@ type NonJsonPrimitive = undefined | Function | symbol;
type IsAny<T> = 0 extends 1 & T ? true : false;

// prettier-ignore
type Serialize<T> =
type Serialize<T> = Pretty<
IsAny<T> extends true ? any :
T extends TypedDeferredData<infer U> ? SerializeDeferred<U> :
T extends JsonPrimitive ? T :
Expand All @@ -28,7 +31,8 @@ type Serialize<T> =
T extends [unknown, ...unknown[]] ? SerializeTuple<T> :
T extends ReadonlyArray<infer U> ? (U extends NonJsonPrimitive ? null : Serialize<U>)[] :
T extends object ? SerializeObject<UndefinedToOptional<T>> :
never;
never
>;

/** JSON serialize [tuples](https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types) */
type SerializeTuple<T extends [unknown, ...unknown[]]> = {
Expand Down