繁体   English   中英

打字稿错误 TS2345 错误:TS2345:“缓冲区”类型的参数不可分配给“字符串”类型的参数

[英]Typescript error TS2345 Error: TS2345:Argument of type 'Buffer' is not assignable to parameter of type 'string'

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

让通信信息 = JSON.parse(newCommunication.content);

TS2345:“缓冲区”类型的参数不可分配给“字符串”类型的参数。

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

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

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

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

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

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

您必须在编译器中禁用 strictNullChecks

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM