Cannot create observable from Observable.bindNodeCallback(fs.readFile) in TypeScript

青春壹個敷衍的年華 提交于 2019-11-30 19:12:41

bindCallback and bindNodeCallback can be tricky with TypeScript, as it all depends upon how TypeScript infers the function parameters.

There is likely a better way, but this is what I do to see exactly what is being inferred: assign the observable to something totally incompatible and look closely at the effected error. For example, this:

const n: number = Observable.bindNodeCallback(fs.readFile);

will effect this error:

Type '(v1: string) => Observable<Buffer>' is not assignable to type 'number'.

So it's obvious that TypeScript is matching the path-only overload of readFile.

In situations like this, I often use an arrow function to specify exactly which overload I want to use. For example, this:

const n: number = Observable.bindNodeCallback((
  path: string,
  encoding: string,
  callback: (error: Error, buffer: Buffer) => void
) => fs.readFile(path, encoding, callback));

will effect this error:

Type '(v1: string, v2: string) => Observable<Buffer>' is not assignable to type 'number'.

So it's now matching the desired overload and the following will work:

let readFileAsObservable = Observable.bindNodeCallback((
  path: string,
  encoding: string,
  callback: (error: Error, buffer: Buffer) => void
) => fs.readFile(path, encoding, callback));

let result = readFileAsObservable('./package.json', 'utf8');
result.subscribe(
  buffer => console.log(buffer.toString()),
  error => console.error(error)
);

To be honest i haven't found a solution, but in order to make it work, i cast it to a function.

(<Function>Rx.Observable.bindNodeCallback(fs.readFile))('./file.txt', 'utf8').subscribe();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!