简体   繁体   English

如何在Typescript接口文件中表示返回类型?

[英]How do I represent a return type in a Typescript interface file?

What is the difference between the following code: 以下代码之间有什么区别:

changeName(): ng.IPromise<any>;

and

changeName: () => ng.IPromise<any>;

I understand one is a return type but I am confused about the first one. 我知道一种是返回类型,但我对第一种感到困惑。

Here's the function body: 这是函数体:

changeName = (): ng.IPromise<any> => {
        var self = this;
        self.chnAction = "PREFERENCES.CHANGE_NAME.SUBMITTING_BUTTON_TEXT";
        self.chnErrorMessage = null;
        return self.uss.changeName(
            self.chnNewFirstName,
            self.chnNewLastName)
            .then(
            (response: ng.IHttpPromiseCallbackArg<any>): any => {
                self.chnAction = "PREFERENCES.CHANGE_NAME.SUBMITTED_BUTTON_TEXT";
                self.chnNewFirstName = '';
                self.chnNewLastName = '';
                self.chnErrorMessage = null;
                self.logout();
                return this.$state.go('home.auth', { content: 'change_name_success' });
            },
            (error: ng.IHttpPromiseCallbackArg<any>): ng.IPromise<any> => {
                if (error.status === 500) {
                    self.chnErrorMessage = 'AUTH_SERVICE.UNABLE_TO_CONTACT_SERVER';
                } else {
                    var errors: string[] = [];
                    Object.keys(error.data.modelState).forEach((key) => {
                        errors.push.apply(errors, error.data.modelState[key]);
                    });
                    self.chnErrorMessage = errors[0];
                    self.chnErrorMessages = errors;
                    self.chnAction = "PREFERENCES.CHANGE_NAME.SUBMIT_BUTTON_TEXT";
                }
                return this.$q.reject(error);
            });
    };

The fundamental difference is this: 根本的区别是:

  • changeName(): ng.IPromise<any>; represents a method . 代表一种方法
  • changeName: () => ng.IPromise<any>; represents a property that can hold a function (this matches changeName = (): ng.IPromise<any> => { ... }; since that is assigning a function to a property). 表示可以容纳函数的属性 (此属性changeName = (): ng.IPromise<any> => { ... };匹配changeName = (): ng.IPromise<any> => { ... };因为这是将函数分配给属性)。

Because of that the differences between properties and methods apply. 因此,属性和方法之间存在差异。 Here's one example: 这是一个例子:

interface MyInterface {
    myMethod(): string;
    myProperty: () => string;
}

class MyBaseClass implements MyInterface {
    myMethod() {
        return "string";
    }

    myProperty = () => "string";
}

class MyChildClass extends MyBaseClass {
    myMethod() {
        return super.myMethod();
    }

    myProperty = () => super.myProperty(); // error
}

The reason why using an arrow function property instead of a method is sometimes done is because arrow functions assigned to properties preserve the value of this no matter what is bound to it... 为什么用箭头功能属性,而不是一个方法有时做的原因是因为分配到的属性箭头功能保存的价值this不管,势必它...

class MyClass {
    myMethod() {
        console.log(this);
    }

    myProperty = () => console.log(this);
}

new MyClass().myMethod.call({});   // outputs {}
new MyClass().myProperty.call({}); // outputs the instance of MyClass

...since the value of this is preserved in the constructor... ......因为价值this是保存在构造函数中...

var MyClass = (function () {
    function MyClass() {
        // captures this here
        var _this = this;
        // guaranteed to always use instance of class for `this`
        this.myProperty = function () { return console.log(_this); };
    }
    MyClass.prototype.myMethod = function () {
        // not guarnateed to always use instance of class
        console.log(this);
    };
    return MyClass;
})();

Sidenote : You can read about .call in JS here . 旁注 :您可以在JS中阅读有关.call信息

It would be better to show whole code sample. 最好显示整个代码示例。 Hopefully the following example will explain your question: 希望以下示例可以解释您的问题:

class MyClass {

    changeName(): number {
        return 5;
    }

    changeName2 = ():number => {
        return 5;
    }
}

transpiles to: 转换为:

var MyClass = (function () {
    function MyClass() {
        this.changeName2 = function () {
            return 5;
        };
    }
    MyClass.prototype.changeName = function () {
        return 5;
    };
    return MyClass;
})();

[ Playground ] [ 游乐场 ]

There is an in-depth explanation of the differences between these two definitions in: Declaring javascript object method in constructor function vs. in prototype 关于以下两个定义之间的差异,有深入的解释: 在构造函数与原型中声明javascript对象方法

On an interface there's no difference. 界面上没有区别。 Here's an interface that uses both notations (let's use string as the return type for clarity): 这是一个使用两种表示法的接口(为了清楚起见,我们使用string作为返回类型):

interface MyInterface {
    foo(): string; // preferred
    bar: () => string;
}

Here, foo is a function with return type string . 在这里, foo是具有返回类型string的函数。 And the type of bar is also a function with the return type string . bar的类型也是带有返回类型string的函数。 The first notation is usually cleaner. 第一个符号通常是更干净的。 The following object matches the interface: 以下对象与接口匹配:

let x: MyInterface = {
    foo: () => "",
    bar: () => ""
}

On a class , one notation is adds the function to the prototype, while the other adds it as a property of the new instance ( this.myFunc = ... ). 类上 ,一种表示法将功能添加到原型,而另一种表示法将其添加为新实例的属性( this.myFunc = ... )。 This has exactly the same effect that it has in JavaScript (and you almost never need to add a function/method as an instance property). 这具有与JavaScript完全相同的效果(并且几乎不需要添加函数/方法作为实例属性)。

class MyClass {
    bar(): string { return ""; } // prototype, preferred
    foo = () => ""; // instance property
}

As we can see below, the class fits our original interface, even though I've reversed foo and bar . 正如我们在下面看到的,即使我已经反转了foobar ,该类也适合我们的原始接口。 Therefore the interface does not impose the implementation detail of how the method will be set. 因此,该接口不会强加如何设置方法的实现细节。

let y: MyInterface = new MyClass();

Note that a class is not a special type - it's effectively an interface plus an implementation. 请注意,类不是特殊类型-实际上是接口和实现。 So you can use MyClass as you would any other type (whether defined as an interface or class): 因此,您可以像使用其他任何类型(无论是定义为接口还是类)一样使用MyClass

let z: MyClass = {
    foo: () => "",
    bar: () => ""
}

With respect to types (which is what an interface defines), there is no difference, though when used in a class the notations produce different implementations. 关于类型(接口定义的类型),没有区别,尽管在类中使用时,表示法会产生不同的实现。

What is the difference between the following code 以下代码有什么区别

As you don't have added more code to see what actually is been configured. 由于您没有添加更多代码来查看实际配置的内容。 As i can see you have two lines of code: 如我所见,您有两行代码:

changeName(): ng.IPromise<any>;

As per this code one can understand that it is returning a promise of type any, which could be anything, an object, string, array, number etc. 按照这段代码,人们可以理解它正在返回类型为any的promise,可以是任何东西, object, string, array, number等。

So one can say that the changeName() will return a ng.IPromise value of type of <any> thing. 因此,可以说changeName()将返回<any>事物类型的ng.IPromise值。


While the other line of code: 而另一行代码:

changeName: () => ng.IPromise<any>;

Says that this function will return a value ng.IPromise of <any> thing. 说这个函数将返回<any>的值ng.IPromise

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM