想给可组合方法添加一个额外的属性,但其抛出错误property 'isActive' does not exist on type '{ id: string; text: string; }'
以下是代码
import { ref, type Ref } from 'vue';
type ActiveItemType = {
text: string;
isActive?: boolean;
};
export const useActiveItems = <T extends ActiveItemType>(data: T[]) => {
let active = '';
function activeMapper(d: T) {
return {
...d,
isActive: d.text === active,
};
}
const itemsData = data.map(activeMapper);
const items = ref(itemsData) as Ref<T[]>;
function onSetActive(text: string) {
active = text;
items.value = items.value.map(activeMapper);
}
// initial set first one
if (items.value[0]) {
items.value[0].isActive = true;
}
return {
items,
onSetActive,
};
};
const { items } = useActiveItems([
{
id: '1',
text: 't1'
},
{
id: '2',
text: 't2'
},
]);
if (items.value[0]) {
items.value[0].isActive; // ERROR
}
TS-运动场-链路
使用hit n trial我发现如果我像这样在我的方法中创建一个类型,它是有效的,但是我不确定它是否正确?或者我们应该只在方法头中创建类型,即在〈〉中?
type U = T & ActiveItemType;
const items = ref(itemsData) as Ref<U[]>;
1条答案
按热度按时间kzipqqlq1#
基于此问题备注:
在泛型中使用
ref
或reactive
时,如果确定该类型没有任何嵌套的引用,则需要强制转换为as Ref<T>
和as reactive<T>
,因为ref和reactive将自动展开嵌套的引用