Skip to content

Allow customization of prop serialization/hydration by supplying custom ser/des functions #3573

@lionel-rowe

Description

@lionel-rowe

Example:

type CustomPropTypeHandler<T, S extends JsonSerializableValue> {
    is(x: unknown): x is T
    serialize(x: T): S
    hydrate(serialized: S): T
}

// prop type I want to make serializable
class Foo {
    constructor(public readonly bar: string) {}
}

// handler
const fooPropTypeHandler: CustomPropTypeHandler<Foo, string> = {
    is: (x) => x instanceof Foo,
    serialize: (x) => x.bar,
    hydrate: (bar) => new Foo(bar),
}

// middleware
app.use((ctx) => {
    ctx.customPropTypeHandlers.push(fooPropTypeHandler)
})

// island component
export function FancyDiv(foo: Foo) {
    <div>{foo.bar}</div>
}

// server-side component/page
<FancyDiv foo={new Foo('hello world')} />

This probably wouldn't make much sense for mutable data, but it'd allow passing around richer data types. It could even work for stringified functions, with the caveat that there'd be footguns, which is less of an issue if it's a userland solution rather than officially supported.

My current, significantly less footgun-prone use case is that I want to add ser/des support for polyfilled Temporal classes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    featNew feature or request

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions