打字稿:界面中的常量

ros*_*han 11 typescript

如何在接口中将常量放在打字稿中.就像在java中一样:

interface OlympicMedal {
  static final String GOLD = "Gold";
  static final String SILVER = "Silver";
  static final String BRONZE = "Bronze";
}
Run Code Online (Sandbox Code Playgroud)

Rya*_*ugh 21

您无法在界面中声明值.

您可以在模块中声明值:

module OlympicMedal {
    export var GOLD = "Gold";
    export var SILVER = "Silver";
}
Run Code Online (Sandbox Code Playgroud)

在即将发布的TypeScript版本中,您将能够使用const:

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

OlympicMedal.GOLD = 'Bronze'; // Error
Run Code Online (Sandbox Code Playgroud)


Bin*_*Ren 7

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

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"'.
}
Run Code Online (Sandbox Code Playgroud)