In my code, I have multiple functions that require a null check on an object before proceeding with certain actions or throwing an error if the object is null. Here is an example of what it looks like:
interface SomeObject {
doThingOne: () => string;
doThingTwo: () => string;
}
let object: SomeObject | null;
function doThingOne() {
if(!object) {
throw new Error('Object is null!');
}
return object.doThingOne();
}
function doThingTwo() {
if(!object) {
throw new Error('Object is null!');
}
return object.doThingTwo();
}
I want to refactor this code by extracting the null check into a separate function to avoid duplication. This is how I attempted to do it:
interface SomeObject {
doThingOne: () => string;
doThingTwo: () => string;
}
let object: SomeObject | null;
function requireObject() {
if(!object) {
throw new Error('Object is null!');
}
}
function doThingOne() {
requireObject();
return object.doThingOne();
}
function doThingTwo() {
requireObject();
return object.doThingTwo();
}
However, after refactoring the code, TypeScript no longer recognizes that object
exists after the null check. Is there a more efficient way to achieve this without losing type inference?
This question on Stack Overflow appears similar, but it doesn't provide a solution that significantly reduces code repetition as I would still need an if
statement.