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

Rah*_*uly 5 node.js typescript

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

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

TS2345:"缓冲区"类型的参数不能分配给"字符串"类型的参数.

我需要投射数据吗?我正在使用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 
            }
        })
    })
}
});
Run Code Online (Sandbox Code Playgroud)

Sur*_*yan 21

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

let communicationInformation = JSON.parse(newCommunication.content.toString());
Run Code Online (Sandbox Code Playgroud)

  • 在这种情况下,不要使用 Buffer().toJSON() ,它看起来是一个优雅的解决方案,但实际上会获取缓冲区的 JSON 表示形式,而不是缓冲区中的字节。例如 `{type:'Buffer', data: [ 123 10, ....]}` (4认同)
  • 或者使用 Buffer().toJSON() (2认同)

Kon*_*zyb 12

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

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