如上图所示,在模板中使用 item prop 时,surface 属性是 unknown 类型。下面是 props 类型定义:
type IWorks = Partial<{
id: string;
text: string;
content: string;
desc: string;
date: string;
view: string;
comm: string;
digg: string;
surface: string;
}>;
defineProps({
item: {
type: Object as PropType<IWorks>,
require: true
},
index: {
type: Number,
required: true
}
});
IWorks 接口类型所有属性都是可选的(由 Partial 工具类型转换)。测试中发现,如果所有的属性都是可选的,就会出现上图所示的错误,只要其中一个属性是必选的,Vue 模板就可以正常推导。具体原因不知。
通过交叉类型运算符 &
把 IWorks 中任一一个属性变成必选的:
defineProps({
item: {
type: Object as PropType<IWorks & { id: string }>,
require: true
}
});