Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript toString('hex') not working

Tags:

typescript

Please someone help me convert a buffer to hex in typescript. I'm getting the error error TS2554: Expected 0 arguments, but got 1. when trying to call data.toString('hex')

const cipher = crypto.createCipher('aes192', config.secret);

let encrypted = '';
cipher.on('readable', () => {
    const data = cipher.read();
    if (data) {
        encrypted += data.toString('hex');
    }
});
cipher.on('end', () => {
    secret = encrypted;
    resolve(encrypted);
});

cipher.write('some clear text data');
cipher.end();

This code example is practically copy and pasted from Node.js docs for crypto

like image 922
Jeremy Avatar asked Aug 02 '17 00:08

Jeremy


1 Answers

cipher.read() returns string | Buffer in which only the type Buffer has the overload for toString that accepts a parameter.

You can try asserting that data is of type Buffer:

encrypted += (data as Buffer).toString('hex');

Or you can use an instanceof type guard:

if (data instanceof Buffer)
    encrypted += data.toString('hex'); // `data` is inferred as `Buffer` here
like image 145
Saravana Avatar answered Sep 22 '22 11:09

Saravana