Typescript: constants in an interface

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

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

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

Tags:

Typescript