【问题标题】:Passing array as arguments in TypeScript在 TypeScript 中将数组作为参数传递
【发布时间】:2013-12-24 22:30:23
【问题描述】:

我有两种方法:

static m1(...args: any[]) {
    //using args as array ...
}

static m2(str: string, ...args: any[]){
    //do something
    //....

    //call to m1
    m1(args);
}

m1(1,2,3) 的调用按预期工作。但是,调用 m2("abc",1,2,3) 将传递给 m1([1,2,3]),而不是像预期的那样:m1(1,2,3)

那么,在m2 中调用m1 时如何将args 作为参数传递?

【问题讨论】:

    标签: arrays typescript arguments


    【解决方案1】:

    其实调用方法时再次使用...就可以了。

    它会在 javascript 中为您生成应用调用。

    static m1(...args: any[]) {
        //using args as array ...
    }
    
    static m2(str: string, ...args: any[]){
        //do something
        //....
    
        //call to m1
    
        // m1(args);
        // BECOMES
        m1(...args);
    }
    

    【讨论】:

    • 是的,这可能在第一次提出问题时不起作用。但这是目前最好的方法。
    【解决方案2】:

    使用Function.prototype.apply:

    T.m1.apply(this, args);
    

    其中 T 是 m1 的封闭类。

    【讨论】:

    • 感谢 Purrfection。它工作得很好!我在调用 apply() 时错过了这个参数,所以 TypeScript 会引发错误。
    • 嗯,需要等待 6 分钟才能接受答案。这是SO的奇怪行为
    • 是的,在这种情况下传递this 将使m1 内的this 引用外部上下文的对象(m2)。仍然需要在m1 内引用m1this
    • 我使用的是 0.9.5,但我的示例不正确。实际上,我的代码是 A.m1() 和 B.m2(),所以我通过调用 m1.apply(A,args) 进行了修复,效果很好。再次感谢您!
    • 不使用此方法。它是javascript,而不是打字稿。使用 Rick Live 的回复 :)
    猜你喜欢
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 2016-09-26
    • 1970-01-01
    • 2010-11-06
    相关资源
    最近更新 更多