Closed
Description
TypeScript Version: 2.2.1
Code
With the code
function filterMap<T, U>(data: Array<T>, fn: (element: T) => U): Array<U> {
let newArray: Array<U> = []
data.forEach(element => {
let newElement = fn(element)
if (newElement != null) {
newArray.push(newElement)
}
})
return newArray
}
let fruits = ['apple', 'banana', 'pear']
let filteredAndMapped = filterMap(fruits, e => e.startsWith('a') ? null : e.toUpperCase())
filteredAndMapped
now have the type Array<string | null>
but in reality only contain elements of type string.
It would be nice if it was possible to do a non-null assertion or similar for types, allowing me to write something similar to
function filterMap<T, U>(data: Array<T>, fn: (element: T) => U): Array<U!> {
let newArray: Array<U!> = []
// ...
so that filteredAndMapped
and newArray
have the type Array<string>
.