在 knockout-2.2.d.ts 中我们有:
interface KnockoutObservableAny extends KnockoutObservableBase {
(): any;
(value): void;
}
我的理解是 (): 用于声明参数列表为空且冒号后为返回类型的函数。
但是我不明白括号前面缺少函数标识符。
我本来期望像 functionName(): any; 这样的东西
这个“匿名”函数是什么意思?我该如何解释这个无名函数,谢谢。
最佳答案
以下接口(interface)描述了一个函数,其作用类似于属性 getter ,这是 JavaScript 世界中的一种常见模式:
interface Property {
//getter
(): string;
}
//assume p: Property;
var value = p(); //The type of value will be a string.
实际上,该接口(interface)等同于此功能类型:
() => string
不同之处在于,在第一个示例中,您可以描述一个具有属性和额外重载的函数:
interface Property {
//getter
(): string;
//setter
(value: string): void;
//register for the change event.
onPropertyChanged(handler: (newValue: string) => void): void;
}
//assume p: Property
var value = p();
p.onPropertyChanged(newValue => { value = newValue; })
p('newValue'); //Would set the value variable to 'newValue'
Knockout 使用遵循此模式的绑定(bind)属性,并且此处描述和示例中使用的语法允许在 TypeScript 中定义此类模式。
至于函数是无名的,你是在声明一个接口(interface)。满足该接口(interface)的每个函数将具有不同的名称。
就个人而言,如果它遵循 C# 中用于索引器的模式,我会发现语法更清晰:
//WARNING: Not valid TypeScript
interface Property {
//getter
this(): string;
//setter
this(value: string): void;
//register for the change event.
onPropertyChanged(handler: (newValue: string) => void): void;
}
在我看来,这种语法更清楚地表明函数声明描述的是实现接口(interface)的对象,而不是其方法之一。
希望对您有所帮助。
关于knockout.js - typescript 中的无名函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21490820/