Typescript: constants in an interface

后端 未结 5 1299
一生所求
一生所求 2020-12-17 14:31

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         


        
相关标签:
5条回答
  • 2020-12-17 15:03

    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

    0 讨论(0)
  • 2020-12-17 15:05

    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"'.
    }
    
    0 讨论(0)
  • 2020-12-17 15:05

    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.

    0 讨论(0)
  • 2020-12-17 15:21

    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
    
    0 讨论(0)
  • 2020-12-17 15:24

    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).

    0 讨论(0)
提交回复
热议问题