withastro / astro

The web framework for content-driven websites. ⭐️ Star to support our work!
https://astro.build
Other
46.82k stars 2.49k forks source link

Cross-collection references are typed weird with Content Layer enabled #12051

Closed tylermercer closed 1 month ago

tylermercer commented 1 month ago

Astro Info

Astro                    v5.0.0-beta.1
Node                     v20.15.0
System                   Windows (x64)
Package Manager          npm
Output                   static
Adapter                  @astrojs/cloudflare
Integrations             @astrojs/sitemap
                         astro-icon
                         astro-meta-tags

If this issue only occurs in one browser, which browser is a problem?

No response

Describe the Bug

I have two Content Layer collections, seasons and episodes. episodes has a season property that is defined as reference('seasons'). But doing things with that reference property is very difficult, due to it's strange type:

(property) season: string | {
    id: string;
    collection: string;
} | {
    slug: string;
    collection: string;
}

image

For example, even though the docs say I can pass this reference property into getEntry directly, I'm unable to do so without getting a cryptic type error:

image

Is this the expected type?

What's the expected result?

The reference property is a type that is both usable in itself without a manual typecheck (e.g. a string or a clearly defined object, but not a union of the two), and it can be passed to getEntry without a type error.

Link to Minimal Reproducible Example

https://github.com/tylermercer/astro-12051-repro

Participation

ascorbic commented 1 month ago

Hi, can you share your content config or ideally share a minimal repro

github-actions[bot] commented 1 month ago

Hello @tylermercer. Please provide a minimal reproduction using a GitHub repository or StackBlitz. Issues marked with needs repro will be closed if they have no activity within 3 days.

tylermercer commented 1 month ago

Here's a repro: https://github.com/tylermercer/astro-12051-repro. Instructions are in the README.

ascorbic commented 1 month ago

Thanks. The issue is that you're using reference inside the loader. While this does work, it's more limited (and we need to document this). It's not able to use the inferred type of the other collection because of how types are generated from schemas in loaders. Loaders don't know anything about other collections, and they're meant to be isolated. This is why it's returning a generic type for the reference. If you move it up into the content config file then it works. I'm going to leave this open because I would like to remove that limitation, but it would still be an anti-pattern to include references inside the loader.

tylermercer commented 1 month ago

That worked, and makes sense! Thank you for your help.