【发布时间】:2020-08-20 23:45:16
【问题描述】:
我正在尝试使用 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
有没有办法限制订阅回调中没有有效参数的以下调用?
【问题讨论】:
-
那么 BehaviourSubject 应该只接受以上 3 种类型作为输入吗?
-
+1 为 miqh 的答案。此外,如果您使用 TS,您可以使用
--strict编译器选项来启用严格的类型检查。查看详情here。
标签: javascript typescript ecmascript-6 rxjs rxjs5