Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Relation Field Typing

default discord avatar
xhomulast year
7

Really appreciate the outstanding work on Local API type inferences! Experiencing a small inconvenience, and wondering if there's an obvious solution I'm missing here.



When requesting a relation field, the return type of the field would be

string | Collection

:



Is there a way to get post, such that the inferred type of post.notes is Note[] only?



I tried with depth:, but that doesn't seem to make a difference.

  • discord user avatar
    denolfe
    last year

    This is one thing we're talking about improving. Possibly passing depth, so the type will be able to properly be inferred as one or the other. More to come!



    Because it could be either based upon depth, it needed to be a union.

  • default discord avatar
    xhomulast year

    Glad to hear!


    Luckily this can be worked around

    (post.note as Note[]).map

    or

    post.notes.map(note => typeof note === "string" ? ... : ...)

    for now.

  • default discord avatar
    unit6last year

    Any updates on this?

  • discord user avatar
    denolfe
    last year

    We haven't made any definitive moves on this. Related conversations are located here:

    https://github.com/payloadcms/payload/discussions/1563

    For the time being, you'll need to use TypeScript type-narrowing. Happy to provide some examples or assistance if you're running into something specific 👍

  • default discord avatar
    unit6last year

    The depth option at the type level seems tricky. Thanks, think type narrowing will be fine for my use case

  • discord user avatar
    denolfe
    last year

    Yep, usually it will come down to doing a

    typeof myValue === 'string'

    or

    typeof myValue === 'object'

    depending on if you're checking it as an ID or the actual collection valuve

  • default discord avatar
    xhomulast year

    FWIW, my workaround was a script similar to what @alamit posted

    https://github.com/payloadcms/payload/discussions/1563#discussioncomment-5357724
Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.