Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't console log in short hand arrow function when using Typescript

When debugging an arrow function in javascript you can write like this:

const sum = (a, b) => console.log(a, b) || a + b;

This will first console log a and b and then return the actual result of the function. But when using Typescript it will complain about console log not being able to be tested for truthiness:

An expression of type 'void' cannot be tested for truthiness

This feels like a valid complaint, but at the same time it's a neat trick to debug arrow functions and I would very much like to not have to add curly braces everywhere I have arrow functions if possible.

Even though the log is only there temporarily, are there any way to get Typescript to accept this pattern without using @ts-ignore?

like image 202
mottosson Avatar asked Dec 31 '22 06:12

mottosson


1 Answers

Change it to use comma operator:

const logger = (a, b) => (console.log(a, b), a + b);
like image 122
Krzysztof Krzeszewski Avatar answered Jan 05 '23 16:01

Krzysztof Krzeszewski