有没有办法只为非库代码启用 strictNullChecks?

Is there a way to only enable strictNullChecks for non-library code?

我已经为我的 TypeScript 应用程序启用了 strictNullChecks。我正在使用用 TypeScript 编写的 RxJS 5。但是,它没有启用 strictNullChecks.

因此,当我执行以下操作时:

Observable.fromEvent(document.getElementById('button'), 'click')

我收到以下错误:

Error TS2345: Argument of type 'HTMLElement | null' is not assignable to parameter of type 'EventTargetLike'.
Type 'null' is not assignable to type 'EventTargetLike'.

换句话说,当 RxJS says 第一个参数应该是一个 EventTargetLike 时,它实际上意味着它应该大致是一个 EventTargetLike | null - 就是这样,在使用他们的 TypeScript 配置时。

有没有办法让 TypeScript 在可用时使用库的配置(即不完全关闭类型检查,如 中所述,这不适用于非默认库)。

what it actually means is that it should be roughly an EventTargetLike | null

可能不会。它实际上需要一个目标,你不应该传递可能为空的东西。快速修复:

let btn = document.getElementById('button');
Observable.fromEvent(btn!, 'click');

你用 ! 告诉编译器我知道 btn 不为 null。或者,您可以进行检查以使编译器满意:

let btn = document.getElementById('button');
if (btn != null){
  Observable.fromEvent(btn, 'click');
}