Can the function throwIfMissing
be modified to only flag test1
as a compiler error?
function throwIfMissing<T>(x: T): T {
if (x === null || x === undefined) {
throw new Error('Throwing because a variable was null or undefined')
}
return x;
}
type Foo = string
// should error:
function test1(x: Foo): Foo {
return throwIfMissing(x);
}
// should NOT error:
function test2(x: Foo | null): Foo {
return throwIfMissing(x);
}
function test3(x: Foo | undefined): Foo {
return throwIfMissing(x);
}
function test4(x: Foo | null | undefined): Foo {
return throwIfMissing(x);
}
Note on solving an "x/y problem": this function serves as a temporary solution for transitioning a codebase's strictNullChecks
setting to true
. As we gradually remove the ... | null | undefined
types, we aim to make unnecessary function calls trigger a compiler error.
I have experimented with using techniques like conditional types, but have not achieved success yet.