30
votes

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

3 Answers

52
votes

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

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

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

You have to disable strictNullChecks in your compiler