How to use kafka-node under typescript?

Viewed 2713

I need to use kafka-node under typescript:

const kafkaHost = 'localhost:9092';
const client = new Client({ kafkaHost });

After launching index.ts I get this error:

 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;

I think problem is in types, so I dont have installed @types/kafka-node, nevertheless it is deprecated.

How to fix it?

2 Answers

kafka-node now comes with it's own pre-defined types for Typescript. You can refer them from here

Regarding your problem, you need the import proper types before using it:

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

const kafkaHost = 'localhost:9092';
const client = new Client({ kafkaHost });

This is a reported bug in kafka-node with no official solution yet. The best answer for this so far is... don't let typescript check kafka-node source code.

Add "skipLibCheck": true to tsconfig.json

see here: https://github.com/SOHU-Co/kafka-node/issues/1412

Related