![](/img/trans.png)
[英]Argument of type 'void' is not assignable to parameter of type 'Function'
[英]How to pass a json response to a function: Argument of type 'unknown' is not assignable to parameter of type 'any[]'
我正在尝试使用来自 api 的数据在函数中使用它:
// Fetch JSON from an external endpoint d3.json('https://api.jsonbin.io/b/5eee6a5397cb753b4d149343').then(data => this.drawBars(data)); private drawBars(data: any[]): void { ... }
但是我收到此错误并且无法弄清楚如何解决它:
错误 TS2345:“未知”类型的参数不可分配给“any[]”类型的参数。 类型 '{}' 缺少类型 'any[]' 的以下属性:length、pop、push、concat 和 26 个更多。
任何指导表示赞赏。
您可以执行以下操作:
d3.json('https://api.jsonbin.io/b/5eee6a5397cb753b4d149343')
.then(data => this.drawBars(data as any[]));
或者,如果您想确保它是一个数组并避免使用 'as' 关键字:
d3.json('https://api.jsonbin.io/b/5eee6a5397cb753b4d149343')
.then(data => {
if(Array.isArray(data) {
this.drawBars(data)
} else {
// throw error or other logic
}
);
这是因为数据的派生类型
unknown
而您正试图将其分配给数组类型的输入。
尝试以下
private drawBars(data: any): void { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.