Matt
Matt

Reputation: 22921

Use the parent class's method types in Typescript

I'm noticing that the types don't flow through when you extend a class and I'm wondering if there's a way to enforce that in the type definition? Here's some psuedo code:

class A {
  render(props: Object) {

  }
}

class B extends A {
  render(props) { <- right now its an any type, I'd like it to inherit from A

  } 
}

I am hoping for something like this:

class A {
  render(props: Object) {

  }
}

class B extends A {
  render(props: this.props) {

  } 
}

Cheers!

Upvotes: 0

Views: 70

Answers (1)

toskv
toskv

Reputation: 31612

You have to redefine the type for that method again. However if you define one that's looser than the base class you'll get an error.

This works:

class A {
  render(props: string) {

  }
}

class B extends A {
    render(props: string) {

  } 
}

This doesn't:

class A {
  render(props: string) {

  }
}

class B extends A {
    render(props: number) {

  } 
}

Upvotes: 2

Related Questions