Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading