Hao*_* Yu 8 rxjs typescript rxjs5
我试图使用rxjs 5在TypeScript中编写Node.js服务器,但是在转换fs.readFile为rxjs表单时遇到错误.我希望以下代码可以在TypeScript中使用
// This is a JavaScript example from the official documentation. It should
// also work at the TypeScript envrionment.
import * as fs from 'fs';
import { Observable } from 'rxjs';
let readFileAsObservable = Observable.bindNodeCallback(fs.readFile);
// This is the line that throws the error.
let result = readFileAsObservable('./roadNames.txt', 'utf8');
result.subscribe(x => console.log(x), e => console.error(e));
Run Code Online (Sandbox Code Playgroud)
但是,当我添加第二个参数时,我的编辑器会报告TypeScript错误 'utf-8'
Supplied parameters do not match any signature of call target.
Run Code Online (Sandbox Code Playgroud)
我试图找到如何使用fs.readFile()in rxjs和TypeScript 的指南,但没有太多运气.
car*_*ant 15
bindCallback并且bindNodeCallback使用TypeScript可能会很棘手,因为它取决于TypeScript如何推断函数参数.
可能有更好的方法,但这就是我要确切看到的内容:将observable分配给完全不兼容的东西并密切关注受影响的错误.例如,这个:
const n: number = Observable.bindNodeCallback(fs.readFile);
Run Code Online (Sandbox Code Playgroud)
会影响这个错误:
Type '(v1: string) => Observable<Buffer>' is not assignable to type 'number'.
Run Code Online (Sandbox Code Playgroud)
所以很明显TypeScript匹配的是仅路径的重载readFile.
在这种情况下,我经常使用箭头函数来准确指定我想要使用的重载.例如,这个:
const n: number = Observable.bindNodeCallback((
path: string,
encoding: string,
callback: (error: Error, buffer: Buffer) => void
) => fs.readFile(path, encoding, callback));
Run Code Online (Sandbox Code Playgroud)
会影响这个错误:
Type '(v1: string, v2: string) => Observable<Buffer>' is not assignable to type 'number'.
Run Code Online (Sandbox Code Playgroud)
所以它现在匹配所需的重载,以下将起作用:
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)
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2259 次 |
| 最近记录: |