1

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('hello\n') // 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.

1 Answer 1

2
+50

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('hello\n')

writehello(process.stdout)
writehello(createWriteStream('/tmp/al.txt'))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.