在TypeScript中使用重命名的方法导出类?

时间:2017-05-22 09:05:04

标签: typescript

在我的代码中,我使用了一个令人惊讶的名为MyClass的类,它有一个方法MyMethod(): void {...},它提供了一个很棒的功能。那些类+方法在很多地方使用过。

现在有一个名为BrandNewClass的全新类(我无法编辑,因为 [插入任何理由会说服你] )只提供一个方法BrandNewMethod(): void {...}以改进的方式提供相同的功能。

为了使用全新功能切换旧功能,我已经摆脱了MyClass(以及MyMethod)。

之后,我可以将对MyClassMyMethod的引用更改为BrandNewClassBrandNewMethod 无处不在

但是,如果我将BrandNewClass重新导出为MyClass并将MyMethod更改为BrandNewMethod,我可以轻松完成工作。

export { BrandNewClass as MyClass } from 'BrandNewClass';

有没有办法进一步简化工作并配置重新导出,因此方法的名称BrandNewMethod也会出现别名(MyMethod)?

2 个答案:

答案 0 :(得分:0)

使用另一个.ts文件来控制案例,假设该文件名为exports.ts

import { MyClass } from "./MyClass";
import { BrandNewClass } from "./BrandNewClass";

export interface IExportClass {
    ClassInstance: any;
    DoThisAwesomeFunction: Function;
}

export function GetExportClass(isNew: boolean): IExportClass {
    var instance;
    if (!isNew) {
        instance = new MyClass();
        return {
            ClassInstance: instance,
            DoThisAwesomeFunction: instance.MyMethod
        }
    }
    else {
        instance = new BrandNewClass();
        return {
            ClassInstance: instance,
            DoThisAwesomeFunction: instance.BrandNewMethod
        }
    }
}

用法:

import { GetExportClass, IExportClass } from "./exports";

// global setting 
var usingNewMethod: boolean = true;

var methodDriver: IExportClass = GetExportClass(usingNewMethod);
methodDriver.DoThisAwesomeFunction();

答案 1 :(得分:0)

export class MyClass extends BrandNewClass {
    constructor() {
        super(); 
        console.log("MyClass is deprecated, use BrandNewClass")
    }

    public MyMethod() { super.BrandNewMethod(); }
}