Adding an extra property to an array of object in composeable method, but ts is complaining about the assignment, event the types are shown correctly
import { ref } from 'vue';
export const useActionLinks = <T extends { icon: string; text: string }>(
data: T[]
) => {
let active = '';
function activeMapper(d: T) {
return {
...d,
isActive: d.text === active,
};
}
const itemsData = data.map(activeMapper);
const items = ref(itemsData);
function onSetActive(text: string) {
active = text;
items.value = items.value.map(activeMapper); // Error: not assignable
}
// initial set first one
if (items.value[0]) {
items.value[0].isActive = true;
}
return {
items,
onSetActive,
};
};
ts error on items.value = items.value.map(activeMapper);
not assignable.
CodePudding user response:
Based on this issue comment :
When using
ref
orreactive
with generics you need to cast toas Ref<T>
andas reactive<T>
if you sure that the type doesn't have any nested refs, because ref and reactive will unwrap nested refs automatically
import {ref, Ref} from 'vue';
// ...
const items = ref(itemsData) as Ref<T[]>;