首页 > 解决方案 > 显示错误的打字稿过滤器不可分配给类型

问题描述

这是行不通的。显示错误 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>

标签: typescript

解决方案


第一段代码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()

推荐阅读