【问题标题】:How to use TypeScript in RxJs (BehaviourSubject) for strict type checking?如何在 RxJs (BehaviourSubject) 中使用 TypeScript 进行严格的类型检查?
【发布时间】: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


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

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

    interface NameSubjectObj {
      a: number;
      b: {
        c: number 
      }
    }
    
    type NameSubject = string | boolean | NameSubjectObj;
    
    const name = new BehaviourSubject<NameSubject>("Dog");
    

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

    【讨论】:

      猜你喜欢
      • 2020-10-30
      • 2021-07-23
      • 1970-01-01
      • 2021-09-07
      • 2019-07-27
      • 1970-01-01
      • 2019-03-23
      • 2020-04-05
      • 1970-01-01
      相关资源
      最近更新 更多