在打字稿中的抽象类实现中,强制静态成员的定义



我正在使用WebSocket消息系统工作,并且需要某种方法来识别消息的类型。我有一个抽象的Message类,然后为每种类型的消息提供一个类,该类都扩展了Message。我已将public static readonly classId声明为Message的成员,然后为Message的每个扩展名设置此值。如果您尝试扩展Message,但不要定义classId,我希望TypeScript会出现错误。怎么能完成?

您无法使用静态方法将抽象降低。如果可能的话,请使用public readonly abstract

abstract class Message {
   public readonly abstract classId: string;
}
interface IMessageParams {
  classId: string;
}
class MessageTypeA extends Message {
  constructor(public readonly classId = "MessageTypeA") {
    super();
  }
}
const msgA1 = new MessageTypeA();
// leaves software for exachage
const json = JSON.stringify(msgA1);
// comes back to software domain
const messageParams: IMessageParams = JSON.parse(json);
// get back your message type A:
const msgA2  = new MessageTypeA(messageParams.classId);
alert(msgA2 instanceof MessageTypeA); //true

最新更新