我正在尝试使用RxJ创建一个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()
和subscribe()
的后续用法。
您可以为BehaviourSubject
创建类型别名,因为它接受类型参数作为泛型的一部分。
interface NameSubjectObj {
a: number;
b: {
c: number
}
}
type NameSubject = string | boolean | NameSubjectObj;
const name = new BehaviourSubject<NameSubject>("Dog");
这将确保上面的BehaviourSubject
接受指定的这3种类型。