Project Graph

高级用法

给构造函数传递额外参数

Sometimes, we need to pass extra arguments to the constructor of a class when deserializing. For example, we may need to pass a database connection to the constructor of a class that needs to access the database.

We can use the @passExtraAtArg1 or @passExtraAtLastArg decorator to pass extra arguments to the constructor.

Of course, you need to pass the extra argument to deserialize.

@passExtraAtLastArg
class File {
  @serializable
  public path: string;

  constructor(
    path: string,
    private fs: FileSystemProvider,
  ) {
    this.path = path;
  }
}

const deserialized = deserialize(json, fileSystemProvider);

In this example, we pass the fileSystemProvider to the constructor of File when deserializing.

给构造函数传递原始对象而不是拆开

@passObject
class User {
  @serializable
  public id: number;

  constructor(obj: { id: number }) {
    this.id = obj.id;
  }
}

const deserialized = deserialize(json);