简体   繁体   English

覆盖打字稿中继承类中的方法声明

[英]Override method declaration in inherited class in typescript

Let's say I have this javascript module that I have imported假设我已经导入了这个 javascript 模块

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?如何从打字稿中的代码段获得有效的 javascript?

TypeScript is pointing out that B is not actually substitutable for A<T1> because B#set is not compatible with A#set . TypeScript 指出B实际上不能替代A<T1>因为B#setA#set不兼容。 To make B substitutable for A<T1> you need to allow for someone to call set with a T1 :要使B替代A<T1>您需要允许某人使用T1调用set

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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