typescript 打字稿:接口中的常量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26471239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript: constants in an interface
提问by roshan
How do I place a constant in an Interface in typescript. Like in java it is:
如何在打字稿的接口中放置常量。就像在java中一样:
interface OlympicMedal {
static final String GOLD = "Gold";
static final String SILVER = "Silver";
static final String BRONZE = "Bronze";
}
回答by Ryan Cavanaugh
You cannot declare values in an interface.
您不能在接口中声明值。
You can declare values in a module:
您可以在模块中声明值:
module OlympicMedal {
export var GOLD = "Gold";
export var SILVER = "Silver";
}
In an upcoming release of TypeScript, you will be able to use const
:
在即将发布的 TypeScript 版本中,您将能够使用const
:
module OlympicMedal {
export const GOLD = "Gold";
export const SILVER = "Silver";
}
OlympicMedal.GOLD = 'Bronze'; // Error
回答by Bing Ren
Just use the value in the interface in place of the type, see below
只需使用接口中的值代替类型,见下文
export interface TypeX {
"pk": "fixed"
}
let x1 : TypeX = {
"pk":"fixed" // this is ok
}
let x2 : TypeX = {
"pk":"something else" // error TS2322: Type '"something else"' is not assignable to type '"fixed"'.
}
回答by NonCreature0714
A recommended way to establish constants in an interface, as shown hereand is similar to another answer here, is to do:
在接口中建立常量的推荐方法(如此处所示,类似于此处的另一个答案)是执行以下操作:
export class Constants {
public static readonly API_ENDPOINT = 'http://127.0.0.1:6666/api/';
public static readonly COLORS = {
GOLD: 'Gold',
SILVER: 'Silver',
BRONZE: 'Bronze'
};
}
This is the preferred way to define constants without being hacky, or disabling settings in the TSLinter(because module and namespace will through many warnings via the linter).
这是定义常量的首选方法,不会被 hacky 或禁用 TSLinter 中的设置(因为模块和命名空间将通过linter发出许多警告)。
回答by Gianpiero
There is a workaround for having constants in a interface: define both the module and the interface with the same name.
有一个在接口中使用常量的解决方法:用相同的名称定义模块和接口。
In the following, the interface declaration will merge with the module, so that OlympicMedal becomes a value, namespace, and type. This might be what you want.
下面,接口声明将与模块合并,从而使 OlympicMedal 成为一个值、命名空间和类型。这可能就是你想要的。
module OlympicMedal {
export const GOLD = "Gold";
export const SILVER = "Silver";
}
interface OlympicMedal /* extends What_you_need */ {
myMethod(input: any): any;
}
This works with Typescript 2.x
这适用于 Typescript 2.x
回答by Jilles van Gurp
This seems to work:
这似乎有效:
class Foo {
static readonly FOO="bar"
}
export function foo(): string {
return Foo.FOO
}
You can have private constants as well like this. It seems interfaces can't have static members though.
您也可以像这样拥有私有常量。接口似乎不能有静态成员。