Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell typescript that an error will be thrown if an argument is null?

Tags:

typescript

Suppose the following:

const handleParse = (arg: { value: boolean } | null) => {
    if (!arg?.value) {
        throw new Error(`\`arg\` is null`)
    }
    
    return arg.value;
}

Here, Typescript knows inline, that the returned arg.value will always be defined.

However, I'm trying to refactor the thrown error to a helper method, but it's throwing an error:

const checkDependency = (dependency: any) => {
    if (!dependency) {
        throw new Error(`\`dependency\` is null`)
    }
}

const handleParse = (arg: { value: boolean } | null) => {
    checkDependency(arg)
    
    return arg.value;
//         ^^^ 'arg' is possible null
}

How can I accomplish this? I've tried playing around with the return type, but to no avail:

const checkDependency = (dependency: any):  Error | void  => {
    if (!dependency) {
        throw new Error(`\`arg\` is null`)
    }

    return;
}
like image 331
Mike K Avatar asked Sep 02 '25 10:09

Mike K


1 Answers

You can use a type assertion function for that combined with a type parameter we combine with null:

function checkDependency<T>(arg: T | null): asserts arg is T {
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^
    if (arg === null) {
        throw new Error(`\`arg\` is null`);
    }
}

Here's your example using that:

const handleParse = (arg: { value: boolean } | null) => {
    checkDependency(arg);
    
    return arg.value; // <== No error
};

Full example on the Playground

Type assertion functions were added in TypeScript v3.7. They're similar to type predicates, but they do exactly what you describe: Indicate that if the function doesn't throw, the type is as the function asserts.

like image 86
T.J. Crowder Avatar answered Sep 03 '25 23:09

T.J. Crowder