带有TypeScript的Rxjs编译错误

时间:2017-01-21 18:33:26

标签: typescript rxjs

以下代码会引发tsc错误,但不确定如何纠正错误。

将rxjs 5.0.3与tsc 2.1.5一起使用

import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/Rx';

let subject = new Subject();

Observable.merge(subject, Observable.interval(500))
  .startWith(new Date())
  .scan((acc, curr) => {
    const date = new Date(acc.getTime());
    date.setSeconds(date.getSeconds() + 1);
    return date;
  })
  .subscribe(v => {
    let today = v.toISOString();
    console.log(today);
  });

我看到的错误是:

node_modules/rxjs/Observable.d.ts(68,60): error TS2304: Cannot find name 'Promise'.
node_modules/rxjs/Observable.d.ts(68,70): error TS2304: Cannot find name 'Promise'.
node_modules/rxjs/observable/PromiseObservable.d.ts(40,31): error TS2304: Cannot find name 'Promise'.
node_modules/rxjs/observable/PromiseObservable.d.ts(41,26): error TS2304: Cannot find name 'Promise'.
node_modules/rxjs/operator/toPromise.d.ts(2,60): error TS2304: Cannot find name 'Promise'.
node_modules/rxjs/operator/toPromise.d.ts(3,79): error TS2304: Cannot find name 'Promise'.
node_modules/rxjs/operator/toPromise.d.ts(3,89): error TS2304: Cannot find name 'Promise'.
test.ts(10,31): error TS2339: Property 'getTime' does not exist on type 'number | {}'.
  Property 'getTime' does not exist on type 'number'.
test.ts(15,19): error TS2339: Property 'toISOString' does not exist on type 'number | {}'.
  Property 'toISOString' does not exist on type 'number'.

2 个答案:

答案 0 :(得分:0)

看起来非常简单,就像你试图打电话一样#34;日期"普通旧数字的方法。 " ACC"这里不会将其解释为日期(或者它已经转换为数字,并且您继续尝试将其视为日期)。

如果我不得不猜测,我会说改变:

const date = new Date(acc.getTime());

const date = new Date(acc).getTime();

可能会遇到那个障碍。或者,因为您要返回" date":

const date = new Date(acc);
date.setSeconds(date.getSeconds() + 1);
return date.getTime ( );

最后:

let today = new Date ( v ).toISOString();
console.log(today);

注意"扫描"的文档(此外,使用"种子"而不是" startWith"可能很有趣):

acc: Any - the accumulated value. 
currentValue: Any - the current value 
index: Number - the current index 
source: Observable - the current observable instance 
[seed] (Any): The initial accumulator value.

答案 1 :(得分:0)

要更正类型错误,请执行以下操作。

acc

对于其他错误,我将currany的类型设置为import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import 'rxjs/Rx'; let subject = new Subject(); Observable.merge(subject, Observable.interval(500)) .startWith(new Date()) .scan((acc: any, curr: any) => { const date = new Date(acc.getTime()); date.setSeconds(date.getSeconds() + 1); return date; }) .subscribe(v => { let today = v.toISOString(); console.log(today); }); 。修正后的代码在这里编译并运行正常。

class="mid"