TypeScriptUtility types
NonNullable<Type>
Removes null and undefined from a type.
Example
#TypeScript
interface Profile {
name: string
avatar?: string | null
}
type Avatar = NonNullable<Profile['avatar']>
// type Avatar = string
const avatars = [null, 'emma.webp', undefined, 'jack.webp']
const present = avatars.filter((a): a is Avatar => a != null)
console.log(present)Result
['emma.webp', 'jack.webp']
Definition and usage
#NonNullable<Type> returns a type without null and undefined. For string | null | undefined the result is string.
It’s useful for types derived from other types, for example from an optional field (NonNullable<User["avatar"]>), or from the result of a function that sometimes returns null.
It doesn’t check anything at runtime. To make sure a value truly isn’t empty, you still need narrowing, such as filtering an array.
Syntax
#Syntax
type New = NonNullable<Type>Type parameters
#Type
any type
The type you are removing null and undefined from.
Good practices
#- The comparison
a != null(with a single=) rejects bothnullandundefinedat once. - Since TypeScript 5.5, the filter
a => a != nullnarrows the array’s type on its own, without an explicit predicate.
Related entries
#Spotted a mistake or missing an example? Write to us.