Issue
I'm using yup to validate a form, and I encountered this type error while trying to make this catch work:
Catch clause variable type annotation must be any or unknown if specified 1196
My Code:
const handleSubmit = async (): Promise<void> => {
try {
const isValid = await userSchema.validate(values, { abortEarly: false });
console.log(isValid);
} catch (err: ValidationError) {
console.log(err);
const errors = getValidationErrors(err);
}
getValidationErrors function:
export function getValidationErrors(err: yup.ValidationError): Errors {
console.error(err);
const validationErrors: Errors = {};
err.inner.forEach((error) => {
if (error.path) validationErrors[error.path] = error.message;
});
return validationErrors;
}
While searching about it, I found out that Typescript doesn't accept types for clause catch arguments... Why is that? This is just so commom in Java or other languages... I mean like... my solution here is attribute err: any... But isn't type any just something to never be used?
Solution
Typescript doesn't let you do that because there's no way that typescript can verify at compile time that the only thing the code can throw is a ValidationError. For that matter, you don't know that either: what if you get a RangeError, because the maximum call stack has been exceeded? Obviously that's unlikely (you'd have to build up a big call stack before calling this), but nothing about this code can guarantee that it won't happen.
This is just so commom in Java or other languages...
Different languages have different constraints on their designs. For example, in Java you can define which errors your function will throw as part of the function definition, as in
public static FileInputStream example(String fileName) throws FileNotFoundException {
Neither javascript nor typescript have a way to specify this in a function definition.
And java lets you have multiple catch blocks, with different types of errors being handled by different ones, but since typescript only exists at compile time, that's not an option. Everything must be handled in a single catch block, and distinguishing which type of error you're dealing with must be done with explicit code.
Answered By - Nicholas Tower
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.