简体   繁体   中英

ES6 Class inherit / extend flow type

My flow type looks like this:

type ModalTypes{
 id: number,
 name: string
}

I would like to inherit the type definition for my class and also reuse it in the constructor:

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

Sadly that doesn't work. I know that I can only extend a class but how can I add some type definitions to my class.
I don't want to write duplicate code like this:

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

Here I am adding id and name twice, once to the Modal class and once to the constructor.
I want to add it only once and prevent duplications.

Just change your type to:

 class ModalTypes {
   id: number,
   name: string
 }

Inheritance isn't really what you need in this instance, even if it might save some typing (no pun intended!)

You can use the utility $PropertyType<> to avoid mismatching types and ensuring consistency at least.

( 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    
  }

}

It's a shame that flow doesn't support spread at class level, like it does at type level, it would save some keyboard time. An alternative approach might be to not extract the properties at class level, but leave them in an object property, thus:

( Try )

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

class Modal {
  props: Props

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

Of course this means more fingerwork whenever you want to access the properties, and may not be what you want in terms of 'own properties' on the object. With the latter approach, you might even be able to use Generics to make reusable classes, which might have some value.

( 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' })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM