Skip to content

Way to specify that type can't be null #14967

Closed
@Pajn

Description

@Pajn

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>.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions