在 TypeScript 中引用另一个函数参数

问题描述 投票:0回答:1

有什么方法可以镜像在父类中可见的类方法参数吗?

澄清的例子:

export abstract class AbstractDoIt {
  protected abstract handle(
    ...params: unknown[]
  ): Promise<void> | void;

  /* "final", not overloaded method */
  public doIt(
    ...handleParams: Parameters<this['handle']> // mirror here
  ): void {
    // pre actions ...
    this.handle(...handleParams);
    // post actions ...
  }
}

class HelloDoIt extends AbstractDoIt {
  protected async handle(a: string, b: number, c: boolean) {
     // here the handle logic
     log('hello')
  }
}

另外一点,使用继承的类

AbstractDoIt

我想:

...

const test = new HelloDoIt();
test.doIt(); // error, the parameters doesn't match with handle(...) defined parameters in HelloDoIt
test.doit("a", 1, null); // error
test.doit("a", 1, true); // magic

...
typescript typescript-typings typescript-generics
1个回答
0
投票

没有办法。抽象类必须独立于任何派生类。

你能做的最好的就是使用

unknown
类型。

© www.soinside.com 2019 - 2024. All rights reserved.