使用枚举在类中强制执行静态成员

时间:2018-02-15 18:15:28

标签: typescript typescript2.0 typescript-2.5

我有这个:

declare enum Foods {
  CHERRY = 'CHERRY',
  LETTUCE = 'LETTUCE',
  JERKY = 'JERKY'
}

declare abstract class ForceFoods {
  static food : Foods
}

export class MyFoods implements ForceFoods {

  static food = Foods.CHERRY;

}

但这是我不知道如何解决的错误:

enter image description here

有谁知道如何解决环境初始化程序错误?

这是错误:

"Initializers are not allowed in ambient contexts"

我有时也会收到此错误:

"Ambient declaration should have no initializer"

2 个答案:

答案 0 :(得分:2)

正如您在评论中提到的,此代码位于声明文件 - .d.ts文件中 - 并且根据您收到的错误而有意义。声明文件中只能包含环境定义(例如declare class MyFoods {}),因为它们用于描述对象的类型信息,而不是它们的实际实现。

顺便说一下,目前还没有办法强制执行静态属性,就像你试图在那里做的那样。有几种选择。例如,您可能希望使用单例模式:

// in a .ts file
export enum Foods {
  CHERRY = 'CHERRY',
  LETTUCE = 'LETTUCE',
  JERKY = 'JERKY'
}

export interface ForceFoods {
  food: Foods;
}

export class MyFoods implements ForceFoods {
  private static _instance: MyFoods | undefined;

  food = Foods.CHERRY;

  private constructor() {
  }

  static get instance() {
    return this._instance || (this._instance = new MyFoods());
  }
}

// then use...
MyFoods.instance.food;

答案 1 :(得分:0)

错误的原因是因为所有代码都在声明文件(.d.ts)中。要修复错误,请将实现类放在.ts文件中:

// index.d.ts

export enum SCEPluginTypes {

  LANGUAGE = 'SCE_LANGUAGE'

}


declare enum Foods {
  CHERRY = 'CHERRY',
  LETTUCE = 'LETTUCE',
  JERKY = 'JERKY'
}


declare abstract class ForceFoods {
  static food : Foods
}

// index.ts

import {Foods, ForceFoods} from "./index";

export class MyFoods implements ForceFoods {

  static food = Foods.CHERRY;

}