简体   繁体   中英

What is the difference between using : and => for the return type with a TypeScript function?

I have the following code:

///<reference path="../typescript/jquery.d.ts" />
function addThemePrototypes() {
    var templateSetup = new Array();
    $.fn.addTemplateSetup = function(func, prioritary)
    {
        if (prioritary)
        {
            templateSetup.unshift(func);
        }
        else
        {
            templateSetup.push(func);
        }
    };
}

Can someone tell me why this should be declared with => void ?

interface JQuery {
    addTemplateSetup: (func: Function, priority: bool) =>void;
}

I guess I am a bit confused about how to do the returntype from a javascript function. Sometimes I see : jQuery and now I am seing => void. What is the difference between the two?

In your example, they are both declared using a colon...

Let's split it in half!

Without the type declaration...

interface JQuery {
    addTemplateSetup
}

The type declaration...

: (func: Function, priority: bool) =>void;

If you use the word is in place of the : it is like saying

The property named 'addTemplateSetUp' : A function accepting two parameters of specific types and not returning a value

Here is an example with two interfaces that are actually identical, but one uses the => and one doesn't. Both are treated identically by TypeScript so it really is down to developer preference.

interface JQuery {
    addTemplateSetup: (func: Function, priority: bool) =>void;
}

interface Identical {
    addTemplateSetup(func: Function, priority: bool): void;
}

class ImplementsEither implements JQuery {
    addTemplateSetup (func: Function, priority: bool) : void {

    }
}

You might use the => style declaration if you like it to read almost in English.

You might use the second style if you want your interfaces to look more like the implementations will.

It is information about what the function returns. Does it return a jQuery object (with the JQuery interface) or is it a void function that does not return anything?

$("#someId").addTemplateSetup();

In your sample you do not return anything, so "void" would be correct. But if you returned "this" instead in your javascript function, as is pretty common, to keep the jQuery chainability, you should declare it returning => JQuery;

$("#someId").addTemplateSetup().Show();

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