报错<html>Vue: Type '{ text: string; id: string; }[]' is not assignable to type 'never[]'.<br/>Type '{ text: string; id: string; }' is not assignable to type 'never'.
出错代码如下:
const onSearch = () => {
// 将所有子标签拿出来拼成一个数组
// console.log(tagList.flatMap(parentTag => parentTag.children))
activeIds.value = tagList.
flatMap(parentTag => parentTag.children)
.filter(item => item.text.includes(searchText.value));
}
问题原因如描述所示,就是类型不匹配,可以用类型断言,将结果显式地指定为
Never
数组类型,你报错不符合什么类型,就显示地指定为什么类型,这样就可以避免类型不匹配的报错。我只想要里边的id就加了一个map
const onSearch = () => {
// 将所有子标签拿出来拼成一个数组
// console.log(tagList.flatMap(parentTag => parentTag.children))
activeIds.value = tagList.
flatMap(parentTag => parentTag.children)
.filter(item => item.text.includes(searchText.value)).map(item => item.id) as [];
}
类型断言并不会改变变量的实际类型,而只是在编译时告诉编译器将其视为特定类型。因此,在使用类型断言时,需要确保代码逻辑和数据类型是一致的,以避免潜在的运行时错误。