I have a function that checks if a dependency is null which wraps another function to guarantee the dependency will not be null:
type Foo = {
doSomething: (s: string) => void;
};
let foo: Foo | null = null;
const checkNull =
<T extends (...args: any[]) => void>(fn: T) =>
(...args: Parameters<T>) => {
if (!foo) {
throw new Error('foo is null');
}
fn();
};
const func = checkNull((s: string) => {
foo.doSomething(s);
/* The above line has the following TypeScript error:
/* 'foo' is possibly 'null'.ts(18047)
*/
});
foo = {
doSomething: (s: string) => {
console.log(s);
},
};
I believe the anonymous function I'm passing to checkNull should never encounter foo that is null, but TypeScript thinks it can possibly still be null here.
Am I missing a way to pass to this wrapped function that we have already null checked foo? For example, the following would work:
const func = (s: string) => {
if (!foo) {
throw new Error('foo is null');
}
foo.doSomething(s);
/* The above line foo can never be null */
}
I'm currently refactoring some vanilla JS to TS, so this is a contrived example, but I'm trying to find a way to pass the null check type guarantee without a major refactor of the underlying logic.