I'm using Astro with strict type checking.
我正在使用带有严格类型检查的Astro。
I have a collection called "portfolio" and I have a couple of conventions for where images are stored for my portfolio. It goes something like:
我有一个名为“公文包”的收藏,我有几个惯例,在哪里存储我的公文包的图像。大概是这样的:
- If portfolioEntry.type = "website" then
- desktopScreenshot = "@content/portfolio/_img/${portfolioEntry.slug}-desktop.png"
- tabletScreenshot = "@content/portfolio/_img/${portfolioEntry.slug}-tablet.png"
- Etc.
Is there any way to attach logic like this to collection entries? It would be great if I was able to:
有没有办法将这样的逻辑附加到集合条目上?如果我能做到这一点就太好了:
let entry = getEntry("portfolio", "foo-2023");
console.log(entry.thumbnail());
Where thumbnail()
is a function that I've attached to the collection, like a method on a class.
其中,Thumb()是我附加到集合中的函数,就像类上的方法一样。
Is there currently any way to achieve this?
目前有什么办法可以做到这一点吗?
What I'm doing currently is:
我目前正在做的是:
function resolvePortfolioThumbnail(entry: any): ImageMetadata {
// ...
}
Which is annoying since I'm not getting any type checking, and in spite of my best effort I couldn't find any way to refer to the portfolio collection type in my function signature.
这很烦人,因为我没有得到任何类型检查,而且尽管我尽了最大努力,我还是找不到任何方法来在我的函数签名中引用Portfolio集合类型。
更多回答
优秀答案推荐
You can type your resolve
helper using Astro’s CollectionEntry
type:
您可以使用Astro的CollectionEntry类型键入Resolve辅助对象:
import type { CollectionEntry } from 'astro:content';
function resolvePortfolioThumbnail(entry: CollectionEntry<'portfolio'>): ImageMetadata {
// ...
}
There’s no built-in way to automatically do this when calling getEntry()
, but you could create a method you use instead:
在调用getEntry()时,没有内置的方法可以自动执行此操作,但您可以创建一个您使用的方法:
import type { ImageMetadata } from 'astro';
import { getEntry, type CollectionEntry } from 'astro:content';
async function getPortfolioEntry(slug: CollectionEntry<'portfolio'>['slug']) {
const entry = await getEntry("portfolio", slug);
return {
...entry,
thumbnail(): ImageMetadata {
// ...
},
};
}
更多回答
我是一名优秀的程序员,十分优秀!