首页 > 解决方案 > 如何在打字稿中将参数从一个具有可变参数数量的函数传递给另一个具有可变参数数量的函数?

问题描述

这不起作用

static myDebug(message: string, ...optionalParameters: any[]): void {
    // tslint:disable-next-line
    console.debug(message, optionalParameters);
}

它只是写这样的行

test myDebug this.url = Array(2), windowId = %d

代替

test myDebug this.url = /myurl, windowId = 123

在 C 中这是无法做到的,所以我需要这样做:

    va_start(Args, Message);
    vsnprintf_s(Buffer, sizeof(Buffer), _TRUNCATE, Format, Args);
    va_end(Args);
    CallTheFunction(Buffer);

标签: typescript

解决方案


如果要记录剩余数组的条目而不是剩余数组本身,请将其展开:

static myDebug(message: string, ...optionalParameters: any[]): void {
    // tslint:disable-next-line
    console.debug(message, ...optionalParameters);
    // --------------------^^^
}

扩展语法在许多方面是对其余语法的补充。

使用它,如果你myDebug这样调用:

myDebug("hi there", 1, 2, 3);

它会这样调用console.debug(有效地):

console.debug(message, optionalParameters[0], optionalParameters[1], optionalParameters[2]);

推荐阅读