Typescript toString('hex')不起作用

时间:2017-08-02 00:36:02

标签: typescript

请有人帮我在打字稿中将缓冲区转换为十六进制。我在尝试拨打error TS2554: Expected 0 arguments, but got 1.

时收到错误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();

此代码示例实际上是从Node.js docs for crypto

复制并粘贴的

1 个答案:

答案 0 :(得分:7)

cipher.read()返回string | Buffer,其中只有类型Buffer具有接受参数的toString的重载。

您可以尝试断言data的类型为Buffer

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

或者您可以使用instanceof type guard

if (data instanceof Buffer)
    encrypted += data.toString('hex'); // `data` is inferred as `Buffer` here