我正在使用一个具有固定,一致的响应结构的API:它始终是一个具有data
属性的对象。由于要在RxJS请求中不断映射数据(或ngrx效果)非常繁琐且过于明确,因此我决定引入一个自定义RxJS运算符,该运算符可以提取数据并应用可选的回调。
但是现在我的一些效果抱怨类型信息(例如:property x doesn't exist on type {}
),所以我想我为适当地保护操作员的I / O所做的努力还不够:
export function mapData<T, R>(callback?: (T) => R) {
return (source: Observable<T>) => source.pipe(
map(value => value['data'] as R), // isn't that an equivalent of `pluck<T>('data')` ?
map(value => typeof callback === 'function' ? callback(value) : value as R),
);
}
带有类型保护问题的ngrx效果示例:
switchMap(() => this.api.getData().pipe(
mapData(),
mergeMap(data => [
new actions.DataSuccessAction({ id: data.id }), // <-- id does not exist on type {}
new actions.SomeOtherAction(data),
]),
catchError(err => of(new actions.DataFailureAction(err))),
)),
当我显式键入它时,当然会消失:
mapData<any, IMyData>(....),
我很想听听这是否是正确的TypeScript处理方式。
答案 0 :(得分:1)
您可以使用多个重载来建模不同的类型行为。我不确定100%的行为应该是什么,您的问题还不确定100%,但是我的阅读建议了以下规则:
T
有data
并且未指定callback
,则返回data
callback
,则返回值由callback
决定callback
并且不适用1,则仅返回T
重载版本看起来像这样:
export function mapData<T, R>(callback: (data: T) => R) : OperatorFunction<T, R>
export function mapData<T extends { data: any }>() : OperatorFunction<T, T['data']>
export function mapData<T>() : OperatorFunction<T, T>
export function mapData<T extends { data? : undefined } | { data: R }, R>(callback?: (data: T) => R) {
return (source: Observable<T>) => source.pipe(
map(value => typeof callback === 'function' ? callback(value) : (value.data ? value.data : value)),
);
}
// Tests
of({ data: { id: 0 }}).pipe(
mapData(),
mergeMap(data => [
new actions.DataSuccessAction({ id: data.id }), // <-- id does not exist on type {}
new actions.SomeOtherAction(data),
]),
catchError(err => of(new actions.DataFailureAction(err))),
)
of({ other: { id: 0 }}).pipe(
mapData(d =>d.other),
mergeMap(data => [
new actions.DataSuccessAction({ id: data.id }), // <-- id does not exist on type {}
new actions.SomeOtherAction(data),
]),
catchError(err => of(new actions.DataFailureAction(err))),
)
of({ data: { id: 0 }}).pipe(
mapData(d =>d.data),
mergeMap(data => [
new actions.DataSuccessAction({ id: data.id }), // <-- id does not exist on type {}
new actions.SomeOtherAction(data),
]),
catchError(err => of(new actions.DataFailureAction(err))),
)
// Filler classes
namespace actions {
export class DataSuccessAction<T>{
constructor(public data:T){}
}
export class SomeOtherAction<T>{
constructor(public data:T){}
}
export class DataFailureAction<T>{
constructor(public data:T){}
}
}