javascript - 将对象作为函数参数传递

标签 javascript typescript

我有 class A,其中一些字段通过 constructorclass B extends class A,任务是为 class A 创建 iterator 这让我有可能将它传递给 super 方法(使用扩展运算符或任何其他方式) . Object.entries() 对我没有帮助。我该怎么做? 我认为这段代码是不言自明的。

class A { 
    constructor(public a: string) { }
}


class B extends A {
    constructor(public b: string, a: A) {
        super(...Object.entries(a));
    }
}

/** can be new B('b', new A('a'));
 * But not the new B('b', 'a') actually 
*/
const b = new B('b', { a: 'a' });  
console.log(b); // expect to get {b: 'b', a: 'a'}
// actually get {b: 'b', a: ['a', 'a']}

最佳答案

给你两个答案:

  • 回答您的问题,以及

  • 提出不同的方法

回答你的问题

我不认为你可以做你所描述的。尽管您可以让 Symbol.iterator 函数以与 A 的构造函数的参数列表相同的顺序返回您创建的数组的迭代器:

class A {
    constructor(public a: string) {
    }

    [Symbol.iterator]() {
        return [this.a][Symbol.iterator]();
    }
}

...问题是 super 调用无法编译,TypeScript 提示:

super(...a); // Expected 1 arguments, but got 0 or more.

当然,除了使用 @ts-ignore 禁用该错误之外,我没有看到解决该问题的方法。 :

// @ts-ignore
super(...a); // Expected 1 arguments, but got 0 or more.

...这似乎不是个好主意。 (Live example 在 Playground 上。)

提出不同的方法

即使你可以这样做,我也不推荐它,它很脆弱:如果你改变了 A 的构造函数中的参数顺序,你需要改变你的迭代器匹配。让它们保持同步将是一个维护陷阱。

相反,我会让构造函数能够接受 A 的实例并复制它的所有属性:

class A {
    public a: string = "";
    constructor(a: string);
    constructor(obj: A);
    constructor(x: string|A) {
        if (x instanceof A) {
            Object.assign(this, x);
        } else {
            this.a = x;
        }
    }
}

super 调用将是:

super(a);

Live example on the playground

关于javascript - 将对象作为函数参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58709555/

相关文章:

javascript - 使用 Promise.all 的最佳实践是什么?

Angular 语法错误 : Unexpected token P in JSON at position 0

Typescript 和 typeorm config .ts 没有重载匹配此调用

javascript - 有没有办法在联合类型上调用数组原型(prototype)方法?

javascript - 无法让我的 RouteProvider 和 Controller 一样工作

javascript - 我如何使用单击的 li 选项填充搜索过滤器 lul ,并将其放置在搜索字段中

javascript - 如何通知即将到来的谷歌地图 API v3

javascript - 如何在 RichFaces 中添加服务器端和客户端事件处理程序

javascript - 文本区域的占位符? (ExtJS)

javascript - TypeScript 中访问者模式的替代方案(避免 instanceof 条件)