【问题标题】:How do I declare the type of a variable to be the type returned by an observable function?如何将变量的类型声明为可观察函数返回的类型?
【发布时间】:2021-03-04 05:04:09
【问题描述】:

我正在调用一个从另一个类返回可观察对象的函数,并且我想将它返回的值分配给一个属性:

class MyComponent {
    prop: ???

    constructor (myService: MyService) {
        myService.observableFunc().subscribe(res => this.prop = res)
    }
}

class MyService {
    observableFunc () {
        return of({foo: "foo", bar: 123})
    }
}

实际的对象要复杂得多,而且它的结构是周期性变化的,所以我不想手动指定它。我如何声明 prop 的类型是(在这种情况下){foo: string, bar: number}

this questionReturnType<typeof MyService.prototype.observableFunc>,它返回可观察对象本身的类型,但我不确定如何从那里获取内部类型。

【问题讨论】:

    标签: typescript rxjs


    【解决方案1】:

    使用ObservedValueOf

    import { ObservedValueOf, of } from 'rxjs';
    
    type Prop = ObservedValueOf<ReturnType<MyService['observableFunc']>>
    
    class MyComponent {
      prop: Prop
    }
    
    class MyService {
      observableFunc() {
        return of({foo: "foo", bar: 123})
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      相关资源
      最近更新 更多