Typescript 从两个泛型类型参数创建联合
下面的代码片段正确地推断出Typescript 从两个泛型类型参数创建联合,typescript,type-inference,Typescript,Type Inference,下面的代码片段正确地推断出change$的返回类型为Observable 或者我可以从属性中获取类型并合并它们吗 getChange$(): Observable<genericTypeOf(propertyA) | genericTypeOf(propertyB)> getChange$():可观察 通常在方法中,此参数是隐式定义的,但您也可以显式定义它,这将允许您从属性中提取必要的类型参数 class Foo { propertyA: Observable<'A'
change$
的返回类型为Observable
或者我可以从属性中获取类型并合并它们吗
getChange$(): Observable<genericTypeOf(propertyA) | genericTypeOf(propertyB)>
getChange$():可观察
通常在方法中,此
参数是隐式定义的,但您也可以显式定义它,这将允许您从属性中提取必要的类型参数
class Foo {
propertyA: Observable<'A' | 'B'> = null as any;
propertyB: Observable<'X' | 'Y'> = null as any;
getChange$<T, U>(this: { propertyA: Observable<T>, propertyB: Observable<U> }): Observable<T | U> {
return merge(
this.propertyA,
this.propertyB
);
}
}
class-Foo{
propertyA:Observable=null,如有;
propertyB:Observable=null,如有;
getChange$(this:{propertyA:Observable,propertyB:Observable}):Observable{
返回合并(
这是我的财产,
这是我的财产
);
}
}
不幸的是,这对我不起作用。我得到这个错误:“模块解析失败:意外的令牌(2:26),您可能需要一个合适的加载程序来处理这个文件类型。”@BetaKeja我以前的解决方案确实有问题。我会更新到一种适合你的不同方法。我想我的例子简化得太多了。MyObservable
s实际上是类属性上的属性;其中一个也是可选的,并且是一个带有字符串文本的联合。我认为这可能比我的情况更复杂。你的第一个解决方案在以后的typescript版本中有效吗?从那以后,我注意到打字稿版本中有一些奇怪的东西。我认为vscode使用3.2.2检查了一些部分,使用2.7.2检查了其他部分(更不用说项目应该使用2.9.2):S@BetaKeja条件类型仅从TypeScript 2.8开始可用
getChange$(): Observable<genericTypeOf(propertyA) | genericTypeOf(propertyB)>
class Foo {
propertyA: Observable<'A' | 'B'> = null as any;
propertyB: Observable<'X' | 'Y'> = null as any;
getChange$<T, U>(this: { propertyA: Observable<T>, propertyB: Observable<U> }): Observable<T | U> {
return merge(
this.propertyA,
this.propertyB
);
}
}