Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript variable that is a typed function

I want to have a variable in a TypeScript class that is of the type "boolean isVisible()".

  1. How do I declare it?
  2. How do I assign this function for another instantiated object to this variable?
  3. How do I call this function?

ps - This seems so basic but 10 minutes of searching and I couldn't find it.

like image 819
David Thielen Avatar asked Nov 06 '13 18:11

David Thielen


2 Answers

function boolfn() { return true; }
function strfn() { return 'hello world'; }

var x: () => boolean;
x = strfn; // Not OK
x = boolfn; // OK

var y = x(); // y: boolean
like image 145
Ryan Cavanaugh Avatar answered Sep 18 '22 12:09

Ryan Cavanaugh


Here's one way of doing it, though I'll be happy to work with you to figure out exactly what you're trying to achieve.

export module Sayings {
    export class Greeter {      
        isVisible(): boolean {
            return true;
        }
    }
}

var greeter = new Sayings.Greeter();
var visible = greeter.isVisible();

You could also use a property instead of a function. Your original question talks about a "variable" and a "function" as if they're the same thing, but that's not necessarily the case.

export module Sayings {
    export class Greeter {      
        isVisible: boolean = false;
    }
}

var greeter = new Sayings.Greeter();
var visible = greeter.isVisible;
greeter.isVisible = true;

Or something like this maybe?

export module Sayings {
    export class Greeter {      
        constructor(public isVisible: () => boolean) {

        }
    }
}

var someFunc = () => {
    return  false;

}

var greeter = new Sayings.Greeter(someFunc);
var visible = greeter.isVisible();
like image 33
Alex Dresko Avatar answered Sep 18 '22 12:09

Alex Dresko