Typescript:接口中的常量

Typescript:接口中的常量,typescript,Typescript,如何在typescript的接口中放置常量。与java一样,它是: interface OlympicMedal { static final String GOLD = "Gold"; static final String SILVER = "Silver"; static final String BRONZE = "Bronze"; } 不能在接口中声明值 您可以在模块中声明值: module OlympicMedal { export var GOLD = "Go

如何在typescript的接口中放置常量。与java一样,它是:

interface OlympicMedal {
  static final String GOLD = "Gold";
  static final String SILVER = "Silver";
  static final String BRONZE = "Bronze";
}

不能在接口中声明值

您可以在模块中声明值:

module OlympicMedal {
    export var GOLD = "Gold";
    export var SILVER = "Silver";
}
在即将发布的TypeScript中,您将能够使用
const

module OlympicMedal {
    export const GOLD = "Gold";
    export const SILVER = "Silver";
}

OlympicMedal.GOLD = 'Bronze'; // Error

在接口中使用常量有一个变通方法:使用相同的名称定义模块和接口

在下文中,接口声明将与模块合并,以便OlympicMedal成为一个值、名称空间和类型。这可能是你想要的

module OlympicMedal {
    export const GOLD = "Gold";
    export const SILVER = "Silver";
}

interface OlympicMedal /* extends What_you_need */ {
    myMethod(input: any): any;
}
这适用于Typescript 2.x

这似乎有效:

class Foo {
  static readonly FOO="bar"
}

export function foo(): string {
  return Foo.FOO
}

您也可以像这样拥有私有常量。但是接口似乎不能有静态成员。

只需使用接口中的值来代替类型,请参见下文

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"'.
}

在接口中建立常数的推荐方法(类似于此处的另一个答案)是:

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'
  };
}

这是定义常量的首选方法,而不必太过粗糙,或者(因为模块和名称空间将通过linter发出许多警告)。

您现在可以使用
tsc--target ES6
编译以下脚本。不幸的是,如果已经将OlympicMedial定义为接口,则会出现这种情况:(你能给接口添加常量吗?