简体   繁体   中英

Override method declaration in inherited class in typescript

Let's say I have this javascript module that I have imported

class A {
  set (k, v) {
  }
}

And I implement my own class based on that module

import A from 'module'

class B extends A {
  set (k, o) {
    super.set(k, o.v)
    // other stuff...
  }
}

This code works fine, but I'm porting my part as typescript (I'm new to typescript). Luckily, the module I'm importing has it's types definition, something like

class A<T> {
  set(k: string, v: T): void;
}

And I'm implementing it like this

class T2 {
  v: T1;
}

class B extends A<T1> {
  set(k: string, o: T2): void {
    super.set(k, o.v)
  }
}

But typescript seems to don't like this. I keep getting this error

Type '(k: string, v: T2) => void' is not assignable to type '(k: string, value: T1): void;'

Not sure how to mutate the arguments of that method. How can I achieve the valid javascript from my snippet in typescript?

TypeScript is pointing out that B is not actually substitutable for A<T1> because B#set is not compatible with A#set . To make B substitutable for A<T1> you need to allow for someone to call set with a T1 :

class B extends A<T1> {
  set(k: string, o: T1 | T2): void {
    if (o instanceof T2) {
      super.set(k, o.v); // Our new overload
    } else {
      super.set(k, o);  // The contract that A<T1> *must* support.
    }
  }
}

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