gpt4 book ai didi

typescript - 从两个泛型类型参数创建联合

转载 作者:搜寻专家 更新时间:2023-10-30 21:34:27 25 4
gpt4 key购买 nike

以下代码片段正确推断出 change$的返回类型为 Observable<'A' | 'B' | 'X' | 'Y'> .

getChange$() {
return merge(
this.propertyA, // Observable<'A' | 'B'>
this.propertyB // Observable<'X' | 'Y'>
);
}

但是,我仍然可以指定返回类型是 Observable 吗? 无需知道 propertyApropertyB的类型参数?

我可以指定类型是Observable吗?但让 TypeScript 仍然推断类型参数?

getChange$(): Observable<?>

或者我可以从属性中获取类型并将它们合并吗?

getChange$(): Observable<genericTypeOf(propertyA) | genericTypeOf(propertyB)>

最佳答案

通常在方法中 this 参数是隐式定义的,但您也可以显式定义它,这将允许您从属性中提取必要的类型参数。

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
);
}
}

关于typescript - 从两个泛型类型参数创建联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53854966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com