如何在RxJs(BehaviourSubject)中使用TypeScript进行严格的类型检查?

问题描述 投票:0回答:2

我正在尝试使用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

是否有任何方法可以限制以下在订阅回调中没有有效参数的调用?

javascript typescript ecmascript-6 rxjs rxjs5
2个回答
3
投票

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

在您的示例中,您可以通过创建string的参数化版本来规定内部值是BehaviorSubject类型,特别是:

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

在这样做时,应将类型检查应用于next()subscribe()的后续用法。


1
投票

您可以为BehaviourSubject创建类型别名,因为它接受类型参数作为泛型的一部分。

interface NameSubjectObj {
  a: number;
  b: {
    c: number 
  }
}

type NameSubject = string | boolean | NameSubjectObj;

const name = new BehaviourSubject<NameSubject>("Dog");

这将确保上面的BehaviourSubject接受指定的这3种类型。

© www.soinside.com 2019 - 2024. All rights reserved.