打字稿中的 Void (条件 && 动作)是什么
What is the Void (conditional && action) in typescript
我以前见过这种语法,如果条件为真,我想做一些事情,我会像这样写出来。
() => void (x === 0 && this.setZero())
为什么要用 void 包裹 x === 0 && this.setZero()
?
这个图案叫什么名字?
Void 将 return undefined 但如果 this.setZero()
return 未定义为什么不这样做呢?
() => x === 0 && this.setZero()
它们都是有效的 ts。用 void 包装它更安全吗?
这只是 JavaScript 的事情。
void
是一个非常奇怪的 JavaScript 运算符:它计算其操作数,然后将 undefined
作为其结果。所以你的
() => void (x === 0 && this.setZero())
... 是一个箭头函数,它总是 return undefined
,调用 this.setZero()
可能产生副作用(如果 x === 0
)。
Why do you wrap x === 0 && this.setZero() in void?
所以函数 always returns undefined
而不是 returning false
(如果 x === 0
为假)或 this.setZero()
的结果(如果 x === 0
为 true
)。
What is the name of this pattern?
具体来说,我认为它没有。
您的 () => x === 0 && this.setZero()
备选方案将 return false
或 this.setZero()
.
的结果
我会注意到
() => void (x === 0 && this.setZero())
做的正是
() => { x === 0 && this.setZero(); }
会,因为冗长的箭头函数不会 return 任何东西,除非你使用 return
;另一种选择是:
() => { if (x === 0) this.setZero(); }
我以前见过这种语法,如果条件为真,我想做一些事情,我会像这样写出来。
() => void (x === 0 && this.setZero())
为什么要用 void 包裹 x === 0 && this.setZero()
?
这个图案叫什么名字?
Void 将 return undefined 但如果 this.setZero()
return 未定义为什么不这样做呢?
() => x === 0 && this.setZero()
它们都是有效的 ts。用 void 包装它更安全吗?
这只是 JavaScript 的事情。
void
是一个非常奇怪的 JavaScript 运算符:它计算其操作数,然后将 undefined
作为其结果。所以你的
() => void (x === 0 && this.setZero())
... 是一个箭头函数,它总是 return undefined
,调用 this.setZero()
可能产生副作用(如果 x === 0
)。
Why do you wrap x === 0 && this.setZero() in void?
所以函数 always returns undefined
而不是 returning false
(如果 x === 0
为假)或 this.setZero()
的结果(如果 x === 0
为 true
)。
What is the name of this pattern?
具体来说,我认为它没有。
您的 () => x === 0 && this.setZero()
备选方案将 return false
或 this.setZero()
.
我会注意到
() => void (x === 0 && this.setZero())
做的正是
() => { x === 0 && this.setZero(); }
会,因为冗长的箭头函数不会 return 任何东西,除非你使用 return
;另一种选择是:
() => { if (x === 0) this.setZero(); }