【发布时间】:2017-12-02 13:30:18
【问题描述】:
我正在学习 Typescript,并且一直在研究这个例子:
interface Thing {
a: number;
b: boolean;
c: string;
}
let obj = <Thing>{
a: 5,
b: true,
c: 'string that says string'
}
function x(someObj: Thing): string {
return someObj.c;
}
function func(someObj: Thing, x: () => string) {
return x(someObj);
}
console.log(func(obj, x))
我在 func 函数的 return 语句中的 x(someObj) 和最后一行对 func 的调用中的 x 都得到相同的错误。
这是错误:
提供的参数与目标的调用签名不匹配
但是,如果我将编译后的版本粘贴到控制台中,它会通过记录“表示字符串的字符串”来工作。
var obj = {
a: 5,
b: true,
c: 'string that says string'
};
function x(someObj) {
return someObj.c;
}
function func(someObj, x) {
return x(someObj);
}
console.log(func(obj, x)); //string that says string
我在 Typescript Playground 中使用编译器:
https://www.typescriptlang.org/play/index.html
我已经查看了有关 stackoverflow 的其他问题和答案,但它们似乎与更复杂的 Angular 问题有关,我不明白。
【问题讨论】:
-
不应该是:
x: (someObj: Thing) => string吗?您必须匹配x的签名,该签名采用接口Thing的一个参数。 -
哦,是的,这行得通。多谢了。我想我想既然我已经在它自己的定义中声明了 x 的类型,那么我就完成了。
标签: javascript typescript