contentlayerdev / contentlayerdev/contentlayer

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

オープン
#76 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る
bug meta: never-stale
主要言語
TypeScript
スター
3.5k
フォーク
192
PR マージ指標
30日以内にマージされた PR はありません

説明

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.

コントリビューションガイド

コントリビューションガイドを開く

調査の方向性

defineDocumentTypeを介して到達する型生成パスから始め、excerptをフィールドと計算フィールドの両方として宣言した、提供されたPost定義を再現します。生成された型にexcerptが1回だけ含まれ、生成されたJSONは変更されないことを確認します。このissueではソースファイルもテストも指定されていないため、ジェネレーターとその型生成のカバレッジを特定することが最初の調査ステップです。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
javascript, typescript
領域
developer-experience, tooling
issue の種類
バグ
難易度
3/5
見積もり時間
1〜2日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
32/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。