Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of lambda expressions in typescript

I'm trying to assign a lambda expression which returns a string, to a property, which, according to the API description, accepts the types (String | Object[] | Function).

 this._popupTemplate.content = (feature) => {
            var template: string; 
            //....
            return template;    
      }

It seems to be working, however, webstorm says "

assigned expression of type (feature:any) => string is not assignable to type string

"

So I tried using a type assertion: <string>(feature) => {...} which seems to have no effect. How can I satisfy webstorm (without suppression the information)?

like image 822
netik Avatar asked Nov 08 '16 14:11

netik


1 Answers

Labmda expression

(feature) => {
    var template: string; 
    //....
    return template;    
}

is just easier way to write normal function like this

function(feature) { 
    var template: string; 
    //....
    return template;
}

The problem is you're trying to assign the function itself, not it's value. You got to execute it first. Add parentheses around the function (or lambda) and then execute it by adding parentheses with arguments after it. Like this:

this._popupTemplate.content = ((feature) => {
        var template: string; 
        //....
        return template;    
    })(feature);
like image 186
Erik Cupal Avatar answered Sep 20 '22 20:09

Erik Cupal