【问题标题】:ES6 Class inherit / extend flow typeES6 类继承/扩展流类型
【发布时间】:2018-03-29 19:17:13
【问题描述】:

我的流类型如下所示:

type ModalTypes{
 id: number,
 name: string
}

我想继承我的类的类型定义并在构造函数中重用它:

class Modal extends ModalTypes {
  constructor(data: ModalTypes) {
    super()
    this.id = data.id
    this.name = data.name
  }
}

很遗憾,这不起作用。我知道我只能扩展一个类,但是如何向我的类添加一些类型定义。
我不想写这样的重复代码:

class Modal{
  id: number
  name: string
  constructor(data: {id: number, name: string}) {
    super()
    this.id = data.id
    this.name = data.name
  }
}

这里我添加了两次idname,一次添加到 Modal 类,一次添加到构造函数。
我只想添加一次并防止重复。

【问题讨论】:

  • 类型只是编译器的东西。类是转译代码的一部分。因此,您不能将类型用作超类,因为它们不存在于代码中。
  • 不要继承以防止重复属性,即继承滥用恕我直言。恕我直言,如果 Modal is ModalType,那么应该驱动继承。如果是,那么继承是有意义的,但如果不是,则不要继承。
  • 是的,对@Nope,我不需要继承。但我想使用相同的类型而不在类和构造函数中定义它们。我想在一个地方定义它们。

标签: javascript reactjs flowtype


【解决方案1】:

只需将您的类型更改为:

 class ModalTypes {
   id: number,
   name: string
 }

【讨论】:

  • 谢谢,但我只想做一些类型检查而不引入新类。这可能吗?它不需要是超类,该类应该只能具有与类型 ModalTypes 相同的类型(因此它不应重复构造函数和类中的类型)
【解决方案2】:

在这种情况下,继承并不是您真正需要的,即使它可以节省一些输入(不是双关语!)

您可以使用实用程序$PropertyType<> 来避免类型不匹配并至少确保一致性。

(Try)

type Props = {
  id: number,
  name: string
}

class Modal {
  id: $PropertyType<Props, 'id'>
  name: $PropertyType<Props, 'name'>

  constructor(data: Props) {
    this.id = data.id
    this.name = data.name    
  }

}

很遗憾,flow 不支持类级别的传播,就像它在类型级别一样,它会节省一些键盘时间。另一种方法可能是不在类级别提取属性,而是将它们保留在对象属性中,因此:

(Try)

type Props = {
  id: number,
  name: string
}

class Modal {
  props: Props

  constructor(props: Props) {
    this.props = props
  }
}

当然,这意味着当您想要访问属性时需要更多的操作,而就对象的“自己的属性”而言,这可能不是您想要的。使用后一种方法,您甚至可以使用泛型来制作可重用的类,这可能会有一些价值。

(Try)

type Props = {
  id: number,
  name: string
}

class Modal<T> {
  props: T

  constructor(props: T) {
    this.props = props
  }
}

const modal: Modal<Props> = new Modal({ id: 1, name: 'bob' })

【讨论】:

    猜你喜欢
    • 2019-05-04
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    相关资源
    最近更新 更多