4

如果我有如下定义的 proto3 消息

message Log {
  string object = 1;
  string key_result = 2;
  string review = 3;
  repeated string tag = 4;

  string begin_at = 5;
  string end_at = 6;
  string created_at = 7;
  string id = 8;
}

protoc with --js_outand会生成类似的--ts_outdts

export class Log extends jspb.Message {
  getObject(): string;
  setObject(value: string): void;

  getKeyResult(): string;
  setKeyResult(value: string): void;

  getReview(): string;
  setReview(value: string): void;

  clearTagList(): void;
  getTagList(): Array<string>;
  setTagList(value: Array<string>): void;
  addTag(value: string, index?: number): string;

  getBeginAt(): string;
  setBeginAt(value: string): void;

  getEndAt(): string;
  setEndAt(value: string): void;

  getCreatedAt(): string;
  setCreatedAt(value: string): void;

  getId(): string;
  setId(value: string): void;

  serializeBinary(): Uint8Array;
  toObject(includeInstance?: boolean): Log.AsObject;
  static toObject(includeInstance: boolean, msg: Log): Log.AsObject;
  static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
  static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
  static serializeBinaryToWriter(message: Log, writer: jspb.BinaryWriter): void;
  static deserializeBinary(bytes: Uint8Array): Log;
  static deserializeBinaryFromReader(message: Log, reader: jspb.BinaryReader): Log;
}

通过方法将Log类转换为对象 很简单。toObject但是要将对象转换为类,我需要手动设置每个字段。

export function toLog(log: Log.AsObject): Log {
    const t = new Log
    t.setObject(log.object)
    t.setKeyResult(log.keyResult)
    t.setReview(log.review)
    t.setTagList(log.tagList)
    t.setBeginAt(log.beginAt)
    t.setEndAt(log.endAt)
    t.setCreatedAt(log.createdAt)
    t.setId(log.id)
    return t
}

有没有更简单的方法来执行这样的任务?

4

0 回答 0