0

Typescript playground

type CUSTOM_REQUEST = {
    someProp: "someValue"
}

const foo = (req: CUSTOM_REQUEST, err: unknown) => {
    console.log(req);
    console.log(err);
};

const someFunction = (req: CUSTOM_REQUEST) => {
    try {
        console.log("ON TRY");
    }
    catch(err) {
        foo(req,err);       // THIS IS OK
        foo(err,req);       // !!! THIS SHOULD NOT BE OK !!!
    }
};

The 2nd call of foo() has got the parameters reversed. And no type errors are being shown.

enter image description here

Second argumennt should be unknown and req: CUSTOM_REQUEST is being passed. That's ok.

But first argument should be req: CUSTOM_REQUEST and err:any is being passed. That should trigger an error, right?

How can I make sure Typescript alert me of this error?

1 Answer 1

2

If something has type any, then it will never show a type error, since any basically disables type checking. So if you want to get a type error, then you'll need to have something other than an any

If you're running typescript 4.0 or later, you can give the err variable the type unknown instead of any:

catch (err: unknown) {
  foo(req,err); // Still ok
  foo(err,req); // Now shows an error, as expected
}

If you want to make sure you always tag your errors as unknown, typescript-eslint has a rule to enforce this: no-implicit-any-catch

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.