How to declare a function that throws an error in Typescript

后端 未结 4 910
孤独总比滥情好
孤独总比滥情好 2020-12-18 18:00

In Java I would declare a function like this:

public boolean Test(boolean test) throws Exception {
  if (test == true)
    return false;
  throw new Excepti         


        
4条回答
  •  太阳男子
    2020-12-18 18:06

    You cannot using pure ts (v<3.9) I hope it will be available in the future. A workaround is however possible, it consists of hiding the possible thrown types in the method's signature to then recover those types in the catch block. I made a package with this workaround here: https://www.npmjs.com/package/ts-throwable/v/latest

    usage is more or less as follow:

    import { throwable, getTypedError } from 'ts-throwable';
    class CustomError extends Error { /*...*/ }
    
    function brokenMethod(): number & throwable {
        if (Math.random() < 0.5) { return 42 };
        throw new CustomError("Boom!");
    }
    
    try {
        const answer: number = brokenMethod()
    }
    catch(error){
        // `typedError` is now an alias of `error` and typed as `CustomError` 
        const typedError = getTypedError(error, brokenMethod);
    }
    
    

提交回复
热议问题