#TS and Astro

1 messages · Page 1 of 1 (latest)

placid mountain
#

Hey! I'm guessing your filteredPosts are just coming from a getCollection('posts')?

If author is a reference you also need to do getEntry to get the author object back from its own content collection

#

Ah ok author isn't a reference!

I think you'll just need to do a check whether author is defined in your map because author is optional in your schema. So name doesn't exist on undefined

#

Or you could filter your posts again before your map to check whether they have author defined

#

Oh sorry! I misread your filter code. Hmmm yeah I'm not sure why that's happening. But I've never used Object.hasOwn before so maybe it just TS not picking it up that it's already filtered.

Maybe try filter(post => !!post.author)? See if author is not a union type in your filteredPosts.

But otherwise you could cast post to a type where author isn't optional. But you'd probably want to make an authorSchema, then cast your post as something like

const PostWithAuthor = Omit<PostSchema, "author"> & {
  author: z.infer<typeof AuthorSchema>
}

filter((post: PostWithAuthor) => {})

But that's a bit of a pain, but would correctly cast your post

#

When I'm at my pc I'll make an astro stackblitz and try it with actual zod. I'm 100% this should work tbh

placid mountain
#

So I've got this, but I only realised at the end that the hover inspect types dealy doesn't work in Stackblitz

https://stackblitz.com/edit/github-3wukzx?file=src%2Fpages%2Findex.astro,src%2Fcontent%2Fposts%2Fpost-one.md,src%2Fcontent%2Fposts%2Fpost-two.md,src%2Fcontent%2Fconfig.ts

I've included the casting your post to the correct type (which is what I do with content collections anyway fwiw). But yeah I can't tell why your filteredPosts wouldn't be getting the correct type with author not | undefined

StackBlitz

Run official live example code for Astro Basics, created by Withastro on StackBlitz