Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: constants in an interface

Tags:

How do I place a constant in an Interface in typescript. Like in java it is:

interface OlympicMedal {   static final String GOLD = "Gold";   static final String SILVER = "Silver";   static final String BRONZE = "Bronze"; } 
like image 358
roshan Avatar asked Oct 20 '14 17:10

roshan


People also ask

Can we have constants in interface?

Interface ConstantsA Java interface can contain constants. In some cases it can make sense to define constants in an interface. Especially if those constants are to be used by the classes implementing the interface, e.g. in calculations, or as parameters to some of the methods in the interface.

Should constants be in interface or class?

You should do it in a class. An Interface is a description of available methods, properties etc that class users can access - by implementing an interface, you guarantee that the members declared in the interface are available to the user.

Why constants should not be defined in interfaces?

That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them.

Should interfaces have constants?

As well, the constants used by a class are typically an implementation detail, but placing them in an interface promotes them to the public API of the class. And hence: Interfaces should only be used to define contracts and not constants!


1 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 an upcoming release of TypeScript, you will be able to use const:

module OlympicMedal {     export const GOLD = "Gold";     export const SILVER = "Silver"; }  OlympicMedal.GOLD = 'Bronze'; // Error 
like image 83
Ryan Cavanaugh Avatar answered Oct 21 '22 19:10

Ryan Cavanaugh