提问者:小点点

强制变量仅承载Javascript中定义的值


我需要设计一个日志消息格式,它有一个名为'type'的属性。 我们已经定义了它可以采用的四种类型,为了简单起见,这些类型被称为A,B,C和D.我想通过枚举的帮助来实现它,但是JavaScript中不存在这样的定义,这就是为什么我想询问如何定义具有值A,B,C和D的“定制”数据类型,以便我的type属性只能采用这四个值中的一个。

提前谢谢你。

export class LogMessageFormat {
  type: myType; //here 'type' should only take the above-mentioned values
  time: String;
  source: String;
  target: String;
}

共1个答案

匿名用户

null

const MessageTypes = {
  A: "A",
  B: "B",
  C: "C",
  D: "D",
};

// If you are concerned with undesired mutation of MessageTypes
// const MessageTypes = Object.freeze({
//   A: "A",
//   B: "B",
//   C: "C",
//   D: "D",
// });


class LogMessageFormat {
  _type = MessageTypes.A
  // .... other props

  get type() {
    return this._type;
  }

  set type(newValue) {

    if (MessageTypes[newValue] === undefined) {
      throw new Error("Invalid message type")
    }

    this._type = newValue;
  }
}

// TEST
const msg = new LogMessageFormat();

console.log(msg.type); // -> log A

msg.type = MessageTypes.B;
console.log(msg.type); // -> log B

msg.type = "no no"; // throws an error