withastro / language-tools

Language tools for Astro
MIT License
240 stars 45 forks source link

🐛 BUG: Type annotation for Astro.props can fail with single property #848

Closed tisonkun closed 3 months ago

tisonkun commented 3 months ago

Describe the Bug

---
const {date}: {date: Date} = Astro.props
const dateMonth = date.toLocaleDateString('default', { month: 'short' })
const dateYearMonth = `${dateMonth} ${date.getFullYear()}`
const dateDayOfMonth = `${date.getDate()}`
---

<div class="col-span-2 text-center">
    <span class="block text-5xl font-semibold">{dateDayOfMonth}</span>
    <span class="block text-sm">{dateYearMonth}</span>
</div>

Steps to Reproduce

Put the code snippet above as a component, run astro check.

Failed with:

src/components/DateTile.astro:2:7 - error ts(2741): Property 'date' is missing in type 'Record<string, any>' but required in type '{ date: Date; }'.

2 const {date}: {date: Date} = Astro.props
        ~~~~~~

Result (19 files): 
- 1 error
- 0 warnings
- 0 hints

 ELIFECYCLE  Command failed with exit code 1.
Princesseuh commented 3 months ago

Astro.props isn't typed (well, it's Record<string, any>) if you don't use a Props interface or cast it. As such, it's no surprise that trying to cast the destructured value will make an error, this is not a bug.

I would recommend to use the official pattern for typing, instead: https://docs.astro.build/en/guides/typescript/#component-props

tisonkun commented 3 months ago

@Princesseuh Interesting. I have other similar code but TS compiler doesn't complain.

LIKE https://github.com/tisonkun/dacapo/blob/084616478eee12ee33d346e922a9fe3d8099062a/src/pages/posts/%5Bslug%5D.astro#L17

https://github.com/tisonkun/dacapo/blob/084616478eee12ee33d346e922a9fe3d8099062a/src/pages/tags/%5Btag%5D.astro#L26

https://github.com/tisonkun/dacapo/blob/084616478eee12ee33d346e922a9fe3d8099062a/src/pages/categories/%5Bcategory%5D.astro#L18

Seems all involves CollectionEntry.

tisonkun commented 3 months ago

Anyway, I use interface Props { method and all works now :D