Rahul Ganguly
Rahul Ganguly

Reputation: 2106

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

I am reading some data from RabbitMQ channel and converting it to a JSON object. I'm getting an error in the following line.

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

The error is,

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 
        }
      })
    })
  }
});

Upvotes: 73

Views: 86296

Answers (3)

Konrad Grzyb
Konrad Grzyb

Reputation: 1985

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'));

Upvotes: 69

Aize
Aize

Reputation: 546

Next Error was error TS2531: Object is possibly 'null'.

You have to disable strictNullChecks in your compiler

Upvotes: -9

Suren Srapyan
Suren Srapyan

Reputation: 68655

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());

Upvotes: 111

Related Questions