[英]typescript, access static member
I am want to have such thing - Api.drinks.info -> which is static and returns string. 我想要这样的东西-Api.drinks.info->这是静态的并返回字符串。 But I have an error
但是我有一个错误
module App {
export class Api {
public static drink: Drink;
}
class Drink {
static get base(): string { return '/api/drink'; }
public static get info(): string { return `${Drink.base}/info`; }
}}
How can I fix it or implement? 如何解决或实施? Thank you.
谢谢。
UPDATE 更新
One of possible solutions 可能的解决方案之一
module Api {
export module Drink {
var base = '/api/drink';
export var info = `${base}/info`;
}
export module Admin {
var base = '/api/drink';
export var info = `${base}/info`;
}}
Api.drink
is not Drink
, the class (constructor), which is what has info
; Api.drink
不是Drink
(类(构造函数)),它是具有info
; it's an instance of Drink
, which does not. 它是
Drink
的一个实例 ,不是。 The line trying to access it is trying to use the instance as though it were the class. 尝试访问它的行试图像使用类一样使用实例。
You don't export Drink
, so the only way to access it is really roundabout: 您不会导出
Drink
,因此访问它的唯一方法实际上是回旋处:
this.resource = this.dataAccessService.getResource(Api.drink.constructor.info);
...But it would be better to export Drink
and use it directly: ...但是最好将
Drink
导出并直接使用:
this.resource = this.dataAccessService.getResource(Drink.info);
Note that the code quoted never assigns a value to the drink
instance, so you'll need to do that with either of the above. 请注意,引用的代码永远不会为
drink
实例分配值,因此您需要使用以上两种方法之一。
Alternately, perhaps you intended to expose Drink
, the constructor, as a static member of Api
? 另外,也许您打算将
Drink
构造函数公开为Api
的静态成员? If so, you need to change things up a bit, see comments: 如果是这样,则需要进行一些更改,请参见注释:
module App {
// Classes aren't hoisted, so this needs to be before Api
class Drink {
static get base(): string { return '/api/drink'; }
public static get info(): string { return `${Drink.base}/info`; }
}
export class Api {
// 1. It's a function
// 2. We're initializing it to Drink
// 3. Because it's a constructor function / class, we use an
// initial capital letter in its name
public static Drink: Function = Drink;
}
}
Then: 然后:
this.resource = this.dataAccessService.getResource(Api.Drink.info);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.