How to enforce generic function parameter to accept only types that include undefined
and null
:
<code>function foo<T>(val: T) { ... }
</code>
<code>function foo<T>(val: T) { ... }
</code>
function foo<T>(val: T) { ... }
<code>let fooNonNullOrUndefined: string = "foo"
foo(fooNonNullOrUndefined) // should not compile because string can neither be null nor undefined
</code>
<code>let fooNonNullOrUndefined: string = "foo"
foo(fooNonNullOrUndefined) // should not compile because string can neither be null nor undefined
</code>
let fooNonNullOrUndefined: string = "foo"
foo(fooNonNullOrUndefined) // should not compile because string can neither be null nor undefined
<code>let fooPossibleNull: string | null = "foo";
foo(fooPossibleNull) // should compile
</code>
<code>let fooPossibleNull: string | null = "foo";
foo(fooPossibleNull) // should compile
</code>
let fooPossibleNull: string | null = "foo";
foo(fooPossibleNull) // should compile
<code>let fooPossibleUndefined: string | undefined = "foo";
foo(fooPossibleUndefined) // should compile
</code>
<code>let fooPossibleUndefined: string | undefined = "foo";
foo(fooPossibleUndefined) // should compile
</code>
let fooPossibleUndefined: string | undefined = "foo";
foo(fooPossibleUndefined) // should compile
<code>let fooPossibleNullOrUndefined: string | null | undefined = "foo";
foo(fooPossibleNullOrUndefined) // should compile
</code>
<code>let fooPossibleNullOrUndefined: string | null | undefined = "foo";
foo(fooPossibleNullOrUndefined) // should compile
</code>
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