Are you looking to include an additional property in a composeable method, but encountering an error stating
property 'isActive' does not exist on type '{ id: string; text: string; }'
Below is the code snippet:
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);
}
// initially set the first item
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
}
Access the TypeScript playground link
Through trial and error, it seems that defining a new type within the method resolves the issue. However, uncertain if this is the correct approach? Or should types only be specified in method headers i.e., within <>?
type U = T & ActiveItemType;
const items = ref(itemsData) as Ref<U[]>;