TypeScript中"not assignable to parameter of type never"错误:原因与解决方案
你好!我开始学习TypeScript,遇到了一个奇怪的错误,无法理解。
我有一个简单的代码,试图过滤数组,移除其中的null和undefined值:
```typescript
const items: (string | null | undefined)[] = ['hello', null, 'world', undefined];
const filteredItems = items.filter(item => item !== null && item !== undefined);
console.log(filteredItems); // 期望:['hello', 'world']
```
但TypeScript报错:`Argument of type '(item: string | null | undefined) => boolean' is not assignable to parameter of type '(value: string | null | undefined, index: number, array: (string | null | undefined)[]) => value is never'`。
我尝试了不同的方法,比如显式指定`filteredItems`的类型,但错误仍然存在。在这个上下文中`never`是什么意思,如何正确过滤数组,让TypeScript知道null和undefined已被移除?
请解释一下发生了什么以及如何修复。提前感谢!