使用流注释具有许多属性的类吗?

时间:2018-11-06 17:56:02

标签: javascript flowtype

我有一个具有许多成员属性的类。所有这些重复看起来很荒谬。有没有那么冗长的注释方法?

type Args = {
  name: string,
  flush_timeout: number,
  close_timeout: number,
  slab_threshold: number,
  slab_fanout: number,
  max_writers: number,
  min_time: EpochObj,
  max_time: EpochObj,
  size: number,
  packet_support: boolean,
  compression: string,
  path: string
}

export default class Space {
  name: string
  flush_timeout: number
  close_timeout: number
  slab_threshold: number
  slab_fanout: number
  max_writers: number
  min_time: EpochObj
  max_time: EpochObj
  size: number
  packet_support: boolean
  compression: string
  path: string

  constructor(args: Args) {
    this.name = args.name
    this.flush_timeout = args.flush_timeout
    this.close_timeout = args.close_timeout
    this.slab_threshold = args.slab_threshold
    this.slab_fanout = args.slab_fanout
    this.max_writers = args.max_writers
    this.min_time = args.min_time
    this.max_time = args.max_time
    this.size = args.size
    this.packet_support = args.packet_support
    this.compression = args.compression
    this.path = args.path
  }
}

2 个答案:

答案 0 :(得分:1)

您可以使用 hack ,即$ReadOnly<Space>代表Space实例成员:

export default class Space {
  name: string
  flush_timeout: number
  ...

  constructor(args: $ReadOnly<Space>) {
    this.name = args.name
    this.flush_timeout = args.flush_timeout
    ...
  }
}

答案 1 :(得分:0)

流中的类为nominally typed,但是我们可以使用type $NominalToStruct<T: {}> = $Exact<$ReadOnly<T>>;

将其转换为结构化类型
class A {
  name: string;
}

// expect error due to nominal types
const a: A = {name: 'Bob'};

// Correct
const a2: $NominalToStruct<A> = {name: 'Bob'};

所以我们可以说Space构造函数接受类空间结构。

export default class Space {
  name: string
  flush_timeout: number
  close_timeout: number

  constructor(args: $NominalToStruct<Space>) {
    this.name = args.name
    this.flush_timeout = args.flush_timeout
    this.close_timeout = args.close_timeout
  }
}

new Space({name: '', flush_timeout: 1, close_timeout: 2})

如果我们的班级有一些额外的字段或方法-我们可以将该构造移到Parent类并使用super

class SpaceChild extends Space {
  extraField: 1;

  constructor(args: $NominalToStruct<Space>){
    super(args);
  }

  extraMethod(){}
}