debugtypescriptCritical
How to declare a function that throws an error in Typescript
Viewed 0 times
errortypescripthowfunctiondeclarethrowsthat
Problem
In Java I would declare a function like this:
And I can use this function without handling the exception.
If it is possible, how to do the same in Typescript? The compiler will tell me that I can't use the function without a try/catch.
public boolean Test(boolean test) throws Exception {
if (test == true)
return false;
throw new Exception();
}And I can use this function without handling the exception.
If it is possible, how to do the same in Typescript? The compiler will tell me that I can't use the function without a try/catch.
Solution
There is no such feature in TypeScript. It's possible to specify error type only if a function returns an error, not throws it (this rarely happens and is prone to be antipattern).
The only relevant type is
When there is a possibility for a function to return a value,
It's possible to specify it in function signature, but for reference only:
It can give a hint to a developer that unhandled error is possible (in case when this is unclear from function body), but this doesn't affect type checks and cannot force
The only relevant type is
never. It is applicable only if a function definitely throws an error, it cannot be more specific than that. It's a type as any other, it won't cause type error as long as it doesn't cause type problems:function Test(): never => {
throw new Error();
}
Test(); // won't cause type error
let test: boolean = Test(); // will cause type errorWhen there is a possibility for a function to return a value,
never is absorbed by return type.It's possible to specify it in function signature, but for reference only:
function Test(test: boolean): boolean | never {
if (test === true)
return false;
throw new Error();
}It can give a hint to a developer that unhandled error is possible (in case when this is unclear from function body), but this doesn't affect type checks and cannot force
try..catch; the type of this function is considered (test: boolean) => boolean by typing system.Code Snippets
function Test(): never => {
throw new Error();
}
Test(); // won't cause type error
let test: boolean = Test(); // will cause type errorfunction Test(test: boolean): boolean | never {
if (test === true)
return false;
throw new Error();
}Context
Stack Overflow Q#49434751, score: 203
Revisions (0)
No revisions yet.