Typescript: constants in the interface

How to place a constant in an interface in typescript. As in java, this is:

interface OlympicMedal { static final String GOLD = "Gold"; static final String SILVER = "Silver"; static final String BRONZE = "Bronze"; } 
+6
source share
3 answers

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 the upcoming TypeScript release, you'll be able to use const :

 module OlympicMedal { export const GOLD = "Gold"; export const SILVER = "Silver"; } OlympicMedal.GOLD = 'Bronze'; // Error 
+19
source

There is a workaround for constants in the interface: define a module and interface with the same name.

Next, the interface declaration is combined with the module, so that OlympicMedal becomes a value, namespace, and type. It may be what you want.

 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

0
source

This seems to work:

 class Foo { static readonly FOO="bar" } export function foo(): string { return Foo.FOO } 

You can have private constants like this. It seems that interfaces cannot have static members.

0
source

Source: https://habr.com/ru/post/976987/


All Articles