这是行不通的。显示错误 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 {\n name: string;\n}\n\nfunction filterPersons(persons: Array<Person | null>): Array<Person> {\n return persons.filter(person => person !== null)\n}\n\nfunction run() {\n const persons: Array<Person | null> = []\n persons.push(null)\n filterPersons(persons)\n}\n\nrun()\n
Run Code Online (Sandbox Code Playgroud)\n但这正在起作用
\ninterface Person {\n name: string;\n}\n\nfunction filterPersons(persons: Array<Person | null>): Array<Person> {\n return persons.filter(person => person !== null) as Array<Person>\n}\n\nfunction run() {\n const persons: Array<Person | null> = []\n persons.push(null)\n filterPersons(persons)\n}\n\nrun()\n
Run Code Online (Sandbox Code Playgroud)\n有什么解释吗?有更好的解决方案吗?谢谢\xef\xb8\x8f
\n第一段代码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()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2411 次 |
最近记录: |