【发布时间】:2016-12-05 20:09:37
【问题描述】:
我正在使用自定义库,对于某些类型我必须编写:
import * as pipeline from 'custom-pipeline';
import {MapTransform} from 'custom-pipeline';
export const createTransform = (appConfig: IAppConfig):
MapTransform<ISomeData, IFoo> |
MapTransform<ISomeData, IBar> => {
switch(appConfig.createType) {
case 'foo':
return new pipeline.MapTransform<ISomeData, IFoo>((data: ISomeData) => {...});
case 'bar':
return new pipeline.MapTransform<ISomeData, IBar>((data: ISomeData) => {...});
}
}
特别是冗长的构造函数让我很恼火。我可以给类型起别名好吗:
type FooTransform = MapTransform<ISomeData, IFoo>;
type BarTransform = MapTransform<ISomeData, IBar>;
但我做不到:
new FooTransform((data: ISomeData) => {...});
new BarTransform((data: ISomeData) => {...});
抛出如下错误:
error TS2304: Cannot find name 'FooTransform'.
我认为这是因为我只有一个类型而不是一个类?然而,我怎样才能以我可以像上面那样做new FooTransform 的方式为构造函数取别名?
MapTransform 的定义如下:
export declare class MapTransform<A, B> extends BaseTransform<A, B> {
constructor(private mapFunc: (val: A) => B);
}
我可以将构造函数简化为:
fooMapFunction = (data: ISomeData): IFoo => {...};
new MapTransform<ISomeData, IFoo>(mapFunction);
尽管它与new FooTransform(fooMapFunction) 不相称。
【问题讨论】:
标签: oop typescript