contentlayerdev / contentlayerdev/contentlayer
Duplicate attributes for DocumentType when using computed Fields to add defaults for normal fields
- Vorherrschende Sprache
- TypeScript
- Sterne
- 3.5k
- Forks
- 192
- PR-Merge-Kennzahlen
- Keine gemergten PRs in 30 T.
Beschreibung
Hi, I'm currently using computed fields to add defaults for optional fields. This results in duplicate attributes in the generated document type classes. Is there another way of defining defaults, or should I approach this differently? If not you might consider adding a bugfix to support this scenario of using computed fields to define defaults.
```js
const computedFields = {
slug: {
type: "string",
resolve: (doc) => doc._raw.sourceFileName.replace(/\.md$/, ""),
},
excerpt: {
type: "string",
resolve: async (doc) => {
if (doc.excerpt) {
return doc.excerpt;
}
const stripped = await remark()
.use(strip)
.process(doc.body.raw.replace(/(<([^>]+)>)/gi, ""));
const excerpt = stripped.toString().slice(0, 500).trim();
return `${excerpt}…`;
},
},
};
export const Post = defineDocumentType(() => ({
name: "Post",
filePathPattern: `posts/*.md`,
fields: {
title: { type: "string", required: true },
publishedAt: { type: "date", required: true },
excerpt: { type: "string", required: false },
},
computedFields,
}));
```
This results in the following:
```js
export type Post = {
/** File path relative to `contentDirPath` */
_id: string
_raw: Local.RawDocumentData
type: 'Post'
title: string
publishedAt: string
excerpt: string | undefined
/** Markdown file body */
body: Markdown
slug: string
excerpt: string
}
```
Despite it works you do see `excerpt` is twice in the `Post` type. Once as `string` and once as `string | undefined`. The generated JSON itself has the field only once as I would expect.
I should probably mention in my project I'm using this from Javascript. That is probably why all still works. In TypeScript this might give some more issues.
Beitragsleitfaden
Rechercherichtung
Beginnen Sie beim Typgenerierungspfad, der über defineDocumentType erreicht wird, und reproduzieren Sie die bereitgestellte Post-Definition, wobei excerpt sowohl als Feld als auch als berechnetes Feld deklariert wird. Überprüfen Sie, dass der generierte Typ excerpt nur einmal enthält, während das generierte JSON unverändert bleibt. Die Issue nennt keine Quelldatei und keinen Test, daher ist das Auffinden des Generators und seiner Abdeckung der Typgenerierung der erste Recherche-Schritt.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- javascript, typescript
- Bereich
- developer-experience, tooling
- Issue-Typ
- Bug
- Schwierigkeit
- 3/5
- Geschätzter Aufwand
- 1-2 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 32/100