typescript 打字稿错误 TS2345 错误:TS2345:“缓冲区”类型的参数不可分配给“字符串”类型的参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46190511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript error TS2345 Error: TS2345:Argument of type 'Buffer' is not assignable to parameter of type 'string'
提问by Rahul Ganguly
new to Typescript. I am reading some data from RabbitMQ channel and am converting it to JSON object. In this line I get the error
打字稿的新手。我正在从 RabbitMQ 通道读取一些数据并将其转换为 JSON 对象。在这一行我得到错误
let communicationInformation = JSON.parse(newCommunication.content);
让通信信息 = JSON.parse(newCommunication.content);
TS2345:Argument of type 'Buffer' is not assignable to parameter of type 'string'.
TS2345:“缓冲区”类型的参数不可分配给“字符串”类型的参数。
Do I need to cast the data? I am using Typescript 2.4.1
我需要投射数据吗?我正在使用打字稿 2.4.1
Amqplib.connect(amqpLibUrl, (err, connection) => {
if (!err) {
connection.createChannel((err, channel) => {
channel.consume('QueueName', newCommunication => {
if (newCommunication != null) {
let communicationInformation = JSON.parse(newCommunication.content);
// Code
}
})
})
}
});
回答by Suren Srapyan
I think the error is thrown on the input parameter of JSON.parse
. Try to first call toString
on it then pass to the function.
我认为错误是在JSON.parse
. 尝试先调用toString
它然后传递给函数。
let communicationInformation = JSON.parse(newCommunication.content.toString());
回答by Aize
Next Error was error TS2531: Object is possibly 'null'.
下一个错误是 error TS2531: Object is possibly 'null'.
You have to disable strictNullChecks in your compiler
您必须在编译器中禁用 strictNullChecks