Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

TS2345:Argument of type 'Buffer' is not assignable to parameter of type 'string'.

Do I need to cast the data? I am using 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 
            }
        })
    })
}
});
like image 301
Rahul Ganguly Avatar asked Sep 13 '17 06:09

Rahul Ganguly


2 Answers

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.

let communicationInformation = JSON.parse(newCommunication.content.toString());
like image 124
Suren Srapyan Avatar answered Oct 19 '22 07:10

Suren Srapyan


I am not sure what is newCommunication.content. In my case it is a file and I had to specify encoding for fs.readFileSync:

 const level = JSON.parse(fs.readFileSync('./path/to/file.json', 'utf-8'));
like image 39
Konrad Grzyb Avatar answered Oct 19 '22 07:10

Konrad Grzyb