在可組合方法中向物件陣列添加額外屬性,但 ts 抱怨分配,事件型別正確顯示
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 錯誤items.value = items.value.map(activeMapper);
無法分配。
打字稿游樂場
uj5u.com熱心網友回復:
基于此問題評論:
當使用
ref或reactive與泛型一起使用時,您需要強制轉換為as Ref<T>并且as reactive<T>如果您確定該型別沒有任何嵌套的參考,因為 ref 和 reactive 會自動解開嵌套的參考
import {ref, Ref} from 'vue';
// ...
const items = ref(itemsData) as Ref<T[]>;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533293.html
標籤:打字稿Vue.jsVuejs3vue-composition-api
