javascript - 如何在 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
有没有办法限制订阅回调中没有有效参数的以下调用?
解决方案
如果您查看BehaviorSubject的类型定义,请注意该类接受泛型类型参数(即BehaviorSubject<T>
)。
string
在您的示例中,您可以通过创建参数化版本来规定内部值是一种类型BehaviorSubject
,具体而言:
const name = new BehaviorSubject<string>("Dog");
这样做时,您应该将类型检查应用于next()
and的后续用法subscribe()
。
推荐阅读
- python - 如何使 PyQt5 QTreeview 节点在代码中可编辑?
- javascript - 使用 React Navigation,如何强制抽屉导航器弹出到堆栈顶部?
- c# - C#:如何转换父级,但只有父级而不是子级
- python-3.x - 如何分析没有真实标签的聚类的完整性?
- typescript - 从基类返回子类的新实例:循环引用
- sql - postgresql 的 ON CONFLICT DO UPDATE 是否会产生大量死元组?
- c - LuaJIT 能比 C 快吗?
- bash - Bash:-d 的使用给出了错误的结果
- javascript - 用于响铃的 Vscode 键盘快捷键
- javascript - Onclick 事件将元素向下移动特定数量的像素