javascript - Can't console log in short hand arrow function when using Typescript - Stack Overflow

When debugging an arrow function in javascript you can write like this:const sum = (a, b) => console

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 plain 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 plaint, 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?

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 plain 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 plaint, 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?

Share Improve this question asked Feb 25, 2020 at 8:29 mottossonmottosson 3,7935 gold badges39 silver badges82 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

Change it to use ma operator:

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

Casting the console.log expression to a boolean should work around this.

For example:

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

Since the expression returns undefined, casting it to boolean would always be false, ensuring any following expression will be returned.

You could overwrite the console type beforehand. Do it once, and you won't have to modify any of your other calls to console.log:

declare const console = {
    log: (...args: unknown[]) => undefined,
    // etc
};

const sum = (a: number, b: number) => console.log(a, b) || 'foo';
const another = (a: number, b: number) => console.log(a, b) || 'bar';

I usually use as below:

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

this is my suggestion. :D

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744773088a4592880.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信