Angular出现TS2571错误:Object is of type 'unknown'如何解决
修复Angular TS2571: Object is of type 'unknown' 错误
错误原因
你项目中的自定义管道listFilter没有显式声明返回值类型,开启TypeScript严格模式后,编译器会默认将其返回值推断为unknown类型,导致遍历后得到的country变量类型不受识别,访问country.name时触发类型校验错误。
修复方案
方案1:为listFilter管道添加明确的类型声明(推荐)
找到你的listFilter管道定义文件,修改管道的transform方法输入、返回值类型为Country[]:
import { Pipe, PipeTransform } from '@angular/core'; import { Country } from './country.model'; // 替换为你项目中Country类型的实际导入路径 @Pipe({ name: 'listFilter' }) export class ListFilterPipe implements PipeTransform { // 明确指定输入值、返回值类型 transform(value: Country[], searchTerm: string): Country[] { if (!value || !searchTerm?.trim()) return value || []; // 此处保留你原有过滤逻辑不变 return value.filter(country => country.name.toLowerCase().includes(searchTerm.trim().toLowerCase()) ); } }
方案2:模板中临时跳过类型校验(应急用,不推荐长期使用)
如果暂时不需要调整管道代码,可以在模板的*ngFor中用$any()方法包裹管道返回值,跳过当前类型校验:
<tr *ngFor=" let country of $any(countries | listFilter: searchTerm) | slice: (page - 1) * pageSize:page * pageSize " > <td style="width: 20px"> {{ country.name }} </td> </tr>
修改完成后重新执行ng serve启动项目即可消除该报错。
内容的提问来源于stack exchange,提问作者Manikandan
相关产品推荐
相关产品推荐

