我试图理解接口和呼叫签名的概念。假设我有以下界面
interface MyInterface {
(x: number, y: string): string;
someProperty: (x: number, y: number) => number;
anotherProperty: number
}
如果我有以下类型声明
let myOtherInterface: MyInterface;
如何正确实现此界面,我尝试了以下但我认为错误
myOtherInterface = {
someProperty = (x, y) => x + y,
public a = doSomething(x, y) => 'a';
}
我还尝试使用以下代码在调用中实现此功能并获取错误
class myClass implements MyInterface {
public a: number;
public someProperty: (x, y) => 1;
public anotherProperty: number = 4;
public anothermethod: (x: number, y: string) => string = (x, y) => y;
doSomething(source: string, subString: string): boolean {
let result = source.search(subString);
return result > -1;
}
}
在课堂上它说呼叫签名不能与MyInterface中给出的签名相匹配。
答案 0 :(得分:2)
TypeScript中没有允许直接实现呼叫签名的语言构造。呼叫签名是added to type system,用于表示现有javascript代码的类型,以启用类型检查调用现有javacsript实现的TypeScript代码。
尽管如此,人们总是可以使用Object.assign
来实现这样的“混合”对象:
interface MyInterface {
(x: number, y: string): string;
someProperty: (x: number, y: number) => number;
anotherProperty: number
}
function impl(x: number, y: string): string {
return 'q';
}
let myOtherInterface: MyInterface = Object.assign(impl, {
someProperty: (x: number, y: number) => 2,
anotherProperty: 3
});
答案 1 :(得分:0)
这是一个例子。跟随TypeScriptLang docs
中的那个if (!mysqli_query($con,$query))
{
echo("Error description: " . mysqli_error($con));
}