[英]TypeScript variable that is a typed function
I want to have a variable in a TypeScript class that is of the type "boolean isVisible()". 我想在TypeScript类中有一个变量,类型为“boolean isVisible()”。
ps - This seems so basic but 10 minutes of searching and I couldn't find it. ps - 这似乎是如此基本,但10分钟的搜索,我找不到它。
function boolfn() { return true; }
function strfn() { return 'hello world'; }
var x: () => boolean;
x = strfn; // Not OK
x = boolfn; // OK
var y = x(); // y: boolean
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.