I am trying to a write a function that takes either writeable stream (createWriteStream) or process.stdout/.stderr but typescript keeps throwing this error. Error goes away when I do conditional type check.
import { createWriteStream, WriteStream } from 'fs' const writehello = (stream: NodeJS.WriteStream & { fd: 1 } | WriteStream) => stream.write('hellon') // error writehello(process.stdout) writehello(createWriteStream('/tmp/al.txt'))
Error message at line 3
error TS2349: This expression is not callable. Each member of the union type '{ (buffer: string | Uint8Array, cb?: ((err?: Error | undefined) => void) | undefined): boolean; (str: string | Uint8Array, encoding?: BufferEncoding | undefined, cb?: ((err?: Error | undefined) => void) | undefined): boolean; } | { ...; }' has signatures, but none of those signatures are compatible with each other.
Advertisement
Answer
Both NodeJS.WriteStream
and WriteStream
overload the write()
method, but they use different signatures, resulting in the error you are seeing.
Instead of defining the union type between these two types, you can define the type of the stream
parameter using Writable
, that is extended by both:
import { createWriteStream } from 'fs' import { Writable } from 'stream' const writehello = (stream: Writable) => stream.write('hellon') writehello(process.stdout) writehello(createWriteStream('/tmp/al.txt'))