【发布时间】:2018-01-21 09:56:27
【问题描述】:
在下面的 TypeScript 中,两个函数是相同的,只是我试图在 demoTwo 中显式声明返回类型。返回类型是一个函数,它本身将一个函数作为输入。我的问题是为什么我必须给出由 whyThis 表示的参数名称,因为它永远不会被使用?如果没有该位置的内容,代码将无法编译。
function demoOne() {
return function(input: () => string) : void {
var result = input();
console.log("Foo:",result);
}
}
function demoTwo(): (whyThis:() => string) => void {
return function(input: () => string) : void {
var result = input();
console.log("Bar:",result);
}
}
var sampleInput = () => "wibble";
demoOne()(sampleInput);
demoTwo()(sampleInput);
要清楚我在这里问的是 Scala 中的等效代码:
object Program {
def demoTwo(): (() => String) => Unit = {
def tmp(input: () => String): Unit = {
val result = input()
println("Bar: " + result)
}
return tmp
}
def main(args: Array[String]): Unit = {
val sampleInput = () => "wibble"
demoTwo()(sampleInput)
}
}
如果我们并排设置 demoTwo 的声明,我们有:
function demoTwo(): (whyThis:() => string) => void { //TS
def demoTwo(): (() => String) => Unit = { //Scala
唯一的主要区别是 TS 在 whyThis 位置需要一些东西,而 Scala 不需要。为什么会这样?
【问题讨论】:
标签: typescript lambda