如何在typescript下使用kafka-node?

5 node.js apache-kafka typescript

我需要在打字稿下使用kafka-node:

const kafkaHost = 'localhost:9092';
const client = new Client({ kafkaHost });
Run Code Online (Sandbox Code Playgroud)

启动index.ts后我收到此错误:

 Property '_write' in type 'ProducerStream' is not assignable to the same property in base type 'Writable'.
  Type '(message: ProduceRequest, encoding: "utf8" | "buffer", cb: (error: any, data: any) => any) => void' is not assignable to type '(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null | undefined) => void) => void'.
    Types of parameters 'encoding' and 'encoding' are incompatible.
      Type 'BufferEncoding' is not assignable to type '"utf8" | "buffer"'.
        Type '"ascii"' is not assignable to type '"utf8" | "buffer"'.

143   _write (message: ProduceRequest, encoding: 'buffer' | 'utf8', cb: (error: any, data: any) => any): void;
Run Code Online (Sandbox Code Playgroud)

我认为问题出在类型上,所以我没有安装@types/kafka-node,但它已被弃用。

如何修复它?

Bri*_*sad 1

kafka-node 现在附带了它自己的 Typescript 预定义类型。您可以从这里参考它们

关于您的问题,您需要在使用之前导入正确的类型:

import { KafkaClient as Client } from 'kafka-node';

const kafkaHost = 'localhost:9092';
const client = new Client({ kafkaHost });
Run Code Online (Sandbox Code Playgroud)