首页 > 解决方案 > 打字稿:将动态数据传递给扩展类

问题描述

我想知道是否有人可以提供帮助?

我有一个需要从 3rdparty 扩展的课程。扩展时我需要动态传递数据 - 因此这是类

class AuthGuardNew extends AuthGuard("Needs changing") {


}

所以我想做的是这样的

new AuthGuardNew("Something different")

在幕后将“不同的东西”传递给扩展类,而不是“需要改变”

如果我使用像这样的构造函数

constructor(type:string) {

}

但是当它已经被扩展时,我怎么能把它传递给 AuthGuard 呢?

有任何想法吗 ?

提前致谢

更新

如果我尝试做

export class AuthGuardNew extends AuthGuard {
  constructor(type?: string) {
    super(type)
  }

我收到一个打字稿错误,说明

Type '(type?: string | undefined) => Type' 不是构造函数类型。

标签: typescript

解决方案


长话短说,你不能。AuthGuard是一个创建类的函数,而不是类。在您知道type.

相反,您可以创建一个新函数,一旦您知道type.

const AuthGuardNew = (type?: string) =>
    class extends AuthGuard(type || 'Needs changing') { 
        // You are free to override anything you need, you are defining a class
        myExtension(): number {
            return 10;
        }
    }

AuthGuardNew又是一个创建类而不是类的函数。

const SomethingDifferentAuthGuard = AuthGuardNew('Something different');

// SomethingDifferentAuthGuard is now a class that extends AuthGuard('Something different') 
// so we can instantiate and use it as such
console.log(new SomethingDifferentAuthGuard().myExtension())

推荐阅读