我正在调用一个函数,该函数从另一个类返回一个可观察的值,我想将它返回的值分配给一个属性:
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}
?
从这个问题中,我得到了ReturnType<typeof MyService.prototype.observableFunc>
,它返回了可观察对象本身的类型,但我不确定如何从那里得到内部类型。
使用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})
}
}