Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip type check on unused parameters

When I compile my typescript project, I'm using the noImplicitAny option so that I won't forget to specify the types on my variables and arguments.

However sometimes you have arguments that you don't use. For example:

jQuery.ajaxTransport("+*", function (options: JQueryAjaxSettings) {   return {     abort: function (_, callback: JQueryCallback) {  

I am not interested in the first argument of the abort function, so I ignore it by naming it _.

Is that the proper way to do that in TypeScript? I couldn't find it in the guide. I suspect that it isn't the proper way, because I can only name one argument _.

Typescript raises the following error:

error TS7006: Parameter '_' implicitly has an 'any' type.

I could just type _:any but that seems a bit overkill for an argument that I don't use.

like image 316
Zyphrax Avatar asked Aug 08 '16 17:08

Zyphrax


Video Answer


1 Answers

I was having the same problem. Using say express and routing you would often only want the res parameter.

router.get('/', function (req, res) { res.end('Bye.'); }); 

Your idea of using _ works here, but I've also found doing this works too.

function (_1, _2, _3, onlyThis) { console.log(onlyThis); } 

This seems better, as only doing '_' I think might make using lodash/underscore a bit confusing, and it also makes it obvious it's the 4th parameter your interested in.

Update: It's been a long time since I posted this answer, and in the comments I'm getting a few miss conceptions. So though I would clarify.

Using the underscore trick is still very useful in Typescript. Like I mentioned in my original answer say if you was using express and did app.get('/', (req, res) => { you will get a warning 'req' is declared but its value is never read, but if you do -> app.get('/', (_req, res) => { the warning will go away. You should not get the error TS7006: Parameter 'req' implicitly has an 'any' type. error anyway, as @types/express should be implicitly typing this param anyway.

like image 150
Keith Avatar answered Sep 22 '22 04:09

Keith