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 S
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.
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
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"'.
}
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.
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
A recommended way to establish constants in an interface, as shown here and 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).