This is not working. Shows error 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()
But this is working
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()
Any explanation & are there any better solution? Thanks ️