contentlayerdev / contentlayerdev/contentlayer

Duplicate attributes for DocumentType when using computed Fields to add defaults for normal fields

Đang mở
#76 1 bình luận 0 reaction 0 người được giao Xem trên GitHub
bug meta: never-stale
Ngôn ngữ chính
TypeScript
Star
3.5k
Fork
192
Chỉ số merge pull request
Không có pull request nào được merge trong 30 ngày

Mô tả

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.

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Đánh giá

Issue này chưa được đánh giá.

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.