How to enforce generic function parameter to accept only types that include undefined
and null
:
function foo<T>(val: T) { ... }
let fooNonNullOrUndefined: string = "foo"
foo(fooNonNullOrUndefined) // should not compile because string can neither be null nor undefined
let fooPossibleNull: string | null = "foo";
foo(fooPossibleNull) // should compile
let fooPossibleUndefined: string | undefined = "foo";
foo(fooPossibleUndefined) // should compile
let fooPossibleNullOrUndefined: string | null | undefined = "foo";
foo(fooPossibleNullOrUndefined) // should compile
Similar to Enforce generic type parameter to be nullish but also accepting/enforcing undefined
.
1