使用TypeScript的方法别名

Ale*_*lls 5 javascript typescript typescript2.0

我认为这是用TS实现方法别名的最简单方法:

export class Foo {

 bar(){

 }

 aliasOfBar(){
   return this.bar.apply(this, arguments);
 }

}
Run Code Online (Sandbox Code Playgroud)

但我只是想知道是否还有另一种方法可以使用TS(或JS)定义别名。理想情况下,可能不需要额外的函数调用。

如果我这样做,例如:

let mySharedFn = function () {

};

export class Foo {
  public bar = mySharedFn
  public aliasBar = mySharedFn
}
Run Code Online (Sandbox Code Playgroud)

它转换为:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var mySharedFn = function () {
};
var Foo = (function () {
    function Foo() {
        this.bar = mySharedFn;
        this.aliasBar = mySharedFn;
    }
    return Foo;
}());
exports.Foo = Foo;
Run Code Online (Sandbox Code Playgroud)

我想避免使用构造函数创建方法等带来的额外调用。

car*_*ant 6

您可以使用接口和原型将别名方法添加到类中,如下所示:

class Person {
    constructor(public name: string) {}
    greet(greeting: string): string { return `${greeting}, ${this.name}`; }
}

interface Person {
    hi: typeof Person.prototype.greet;
}
Person.prototype.hi = Person.prototype.greet;

const p = new Person("Alice");
console.log(p.greet("Hey"));
console.log(p.hi("Hi"));
Run Code Online (Sandbox Code Playgroud)