首页 > 解决方案 > 如何在 RxJs (BehaviourSubject) 中使用 TypeScript 进行严格的类型检查?

问题描述

我正在尝试使用 RxJs 创建一个 BehaviourSubject。在这段代码中

import { BehaviourSubject } from 'rxjs';

const name = new BehaviourSubject("Dog");

// Here in the subscribe callback, I am using TypeScript to specify the argument type should be string.
name.subscribe((name: string):void => {console.log(name)});
name.next("cat"); //cat

我想限制这些下面的调用,因为我需要在上面提到的订阅回调中传递一个字符串作为参数。

name.next(5); // This will print 5
name.next({a:5,b:{c:10}}); // This will print the object
name.next(true); // This will print true

有没有办法限制订阅回调中没有有效参数的以下调用?

标签: javascripttypescriptecmascript-6rxjsrxjs5

解决方案


如果您查看BehaviorSubject的类型定义,请注意该类接受泛型类型参数(即BehaviorSubject<T>)。

string在您的示例中,您可以通过创建参数化版本来规定内部值是一种类型BehaviorSubject,具体而言:

const name = new BehaviorSubject<string>("Dog");

这样做时,您应该将类​​型检查应用于next()and的后续用法subscribe()


推荐阅读