typescript - 显示错误的打字稿过滤器不可分配给类型
问题描述
这是行不通的。显示错误 Type '(Person | null)[]' is not assignable to type 'Person[]'. Type 'Person | null' is not assignable to type 'Person'. Type 'null' is not assignable to type 'Person'.
interface Person {
name: string;
}
function filterPersons(persons: Array<Person | null>): Array<Person> {
return persons.filter(person => person !== null)
}
function run() {
const persons: Array<Person | null> = []
persons.push(null)
filterPersons(persons)
}
run()
但这是有效的
interface Person {
name: string;
}
function filterPersons(persons: Array<Person | null>): Array<Person> {
return persons.filter(person => person !== null) as Array<Person>
}
function run() {
const persons: Array<Person | null> = []
persons.push(null)
filterPersons(persons)
}
run()
任何解释&有没有更好的解决方案?谢谢️</p>
解决方案
第一段代码persons.filter(person => person !== null)
没有进行类型检查,因为 TSC 无法理解您的代码实际上是在将数组项类型缩小为Person
.
您可以通过将过滤器函数声明为类型保护来帮助它。游乐场。
interface Person {
name: string;
}
// notice person is Person return type
const isPerson = (person: Person | null) : person is Person => person !== null
function filterPersons(persons: Array<Person | null>): Array<Person> {
return persons.filter(isPerson)
}
function run() {
const maybePersons: Array<Person | null> = []
maybePersons.push(null)
const persons: Person[] = filterPersons(maybePersons)
console.log(persons)
}
run()
推荐阅读
- java - OOP 中“抽象”的正确定义是什么?
- python - str.replace 除非字符串后跟某些文本
- python - 将列表元素分成单独的数字并写入记事本文件
- python - Python:我可以使 read_excel sheet_name 不区分大小写吗
- node.js - 节点 cron 在特定日期后每 7 天运行一次
- android - 如何在 onclick 中使用私有 void?
- python - 如何打印字典的名字?
- python - NumPy 矩阵运算在不同的机器上产生不同的结果
- firebase - 挣扎于 Flutter 中的 authStateChanges
- php - 在php中将数组键转换为字符串