-
Notifications
You must be signed in to change notification settings - Fork 12.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Return type of a function that calls an error throwing function #13625
Comments
function throwError(message: string): never {
throw new Error(message);
} then you can just use this in you other function as such: function foo(): number {
return throwError('message');
}
|
Cool thanks! |
Quickly hijacking this issue for a short question. Does the explanation you gave, @mhegazy, imply one should add |
never is a type that u should not witness at runtime. It should never happen, hence the name. So a function returns a number, that is the normal execution behavior, use that in return type annotation. More in https://www.typescriptlang.org/docs/handbook/basic-types.html#never |
It's worth noting that calling a function with a return type of never doesn't behave the same as just throwing an error because of unassigned variable errors: function throwError (msg: string): never {
throw new Error('My custom error prefix: ' + msg);
}
let myString: string;
if (Math.random() < 0.5) {
myString = 'hello world';
} else {
throwError('hello error');
}
console.log(myString); // [ts] Variable 'myString' is used before being assigned. So if you're doing something like the above, you'll need to return on every function that returns never: let myString: string;
if (Math.random() < 0.5) {
myString = 'hello world';
} else {
return throwError('hello error');
}
console.log(myString); // No error Be aware, however, that since you can't return in the global scope, I don't think there's anything you can do about the error in that case other than using the definite assignment assertion: let myString!: string;
// ...
console.log(myString); // No error |
TypeScript Version: 2.1.1
Code
My use case is I'm writing some library code, where there's an interface as follows:
There are some modules implementing this interface, however
foo
is an optional method thus not all implementations will havefoo
method. When someone callsfoo
, instead of causing a Javascript errorundefined is not a function
, I'd prefer to throw a more descriptive error, preferably usingthrowError
function.I assume this would be tricky to implement.
The text was updated successfully, but these errors were encountered: