简体   繁体   中英

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).

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...

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...

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 .

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

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):

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

Here, foo is a function with return type string . And the type of bar is also a function with the return type 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 has exactly the same effect that it has in JavaScript (and you almost never need to add a function/method as an instance property).

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 . 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):

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.

So one can say that the changeName() will return a ng.IPromise value of type of <any> thing.


While the other line of code:

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

Says that this function will return a value ng.IPromise of <any> thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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