打字稿错误TS2345错误:TS2345:类型'缓冲区'的参数不能分配给' string'类型的参数。

时间:2017-09-13 06:39:43

标签: node.js typescript

打字稿的新手。我正在从RabbitMQ通道读取一些数据并将其转换为JSON对象。在这一行我得到错误

让communicationInformation = JSON.parse(newCommunication.content);

TS2345:类型'缓冲区'不能分配给' string'。

类型的参数

我需要投射数据吗?我正在使用Typescript 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 
            }
        })
    })
}
});

3 个答案:

答案 0 :(得分:13)

我认为错误是JSON.parse的输入参数引发的。尝试先调用toString然后传递给函数。

let communicationInformation = JSON.parse(newCommunication.content.toString());

答案 1 :(得分:7)

我不确定什么是 newCommunication.content。就我而言,它是一个文件,我必须为 fs.readFileSync 指定编码:

 const level = JSON.parse(fs.readFileSync('./path/to/file.json', 'utf-8'));

答案 2 :(得分:0)

下一个错误是error TS2531: Object is possibly 'null'.

您必须在编译器中禁用strictNullChecks

相关问题