使用@nuxt/content遇类型错误:ParsedContent|null无法赋值给Record<string,any>|undefined
解决@nuxt/content中vue-tsc类型不匹配错误
问题场景
测试@nuxt/content时,自定义ParsedContent接口并使用queryContent.findOne()查询内容,在将结果传给ContentRenderer组件时触发vue-tsc错误:
Type 'ParsedContent | null' is not assignable to type 'Record<string, any> | undefined'
相关文件内容:
/content/news/test.md
--- title: 'test' tag: ['test'] --- # test1 content
/pages/my-page.vue
<script setup lang="ts"> import type { ParsedContent } from '@nuxt/content/dist/runtime/types' interface MyCustomParsedContent extends ParsedContent { tag: Array<string> } const { data:article } = await useAsyncData(() => queryContent<MyCustomParsedContent>('news') .where({ tag: { $in: ['patch-note'] } }) .sort({ date: -1 }) .findOne()) if (!article.value) { throw createError({ statusCode: 404, statusMessage: "Page not found", }); } </script> <template> <div> <ContentRenderer :value="article" /> </div> </template>
问题原因
queryContent.findOne()返回Promise<MyCustomParsedContent | null>,导致useAsyncData生成的article类型为Ref<MyCustomParsedContent | null>。虽然代码中已经通过throw createError处理了null情况,但TypeScript在模板中无法自动推断article已排除null状态,与ContentRenderer期望的Record<string, any> | undefined类型不兼容。
解决方案
方案1:类型断言指定data类型
直接通过类型断言,告诉TypeScriptuseAsyncData返回的data是排除null的Ref类型:
const { data: article } = await useAsyncData(() => queryContent<MyCustomParsedContent>('news') .where({ tag: { $in: ['patch-note'] } }) .sort({ date: -1 }) .findOne() ) as { data: Ref<MyCustomParsedContent> }
方案2:模板中使用非空断言
在模板里给article添加非空断言,强制说明其不为null:
<ContentRenderer :value="article!" />
方案3:手动转换为确定类型的ref
先声明确定类型的ref,在null检查后手动赋值,确保类型安全:
import type { ParsedContent } from '@nuxt/content/dist/runtime/types' interface MyCustomParsedContent extends ParsedContent { tag: Array<string> } // 声明确定类型的ref const article = ref<MyCustomParsedContent>() const { data } = await useAsyncData(() => queryContent<MyCustomParsedContent>('news') .where({ tag: { $in: ['patch-note'] } }) .sort({ date: -1 }) .findOne() ) if (!data.value) { throw createError({ statusCode: 404, statusMessage: "Page not found", }); } // 手动赋值,确保类型非空 article.value = data.value
以上三种方案都可以解决类型不匹配的问题,可根据个人代码风格选择。
内容的提问来源于stack exchange,提问作者Tib
相关产品推荐
相关产品推荐

