6

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.

2
  • Where do you want to call the function from? Commented Nov 6, 2013 at 18:25
  • Once I have it assigned then I want to be able to call "var isV = myObj.func()" - or however that would work. Commented Nov 6, 2013 at 18:27

2 Answers 2

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

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

var y = x(); // y: boolean
Sign up to request clarification or add additional context in comments.

Comments

2

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();

2 Comments

Sorry, no. The function does not exist in the class. Just a var that holds the address of the function. So isVisible is a variable.
Where does the function come from?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.