You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript 2.8.1中out/ref关键字使用及多返回值获取咨询

解决方案:在TypeScript中同时返回多个值

当然可以实现!在TypeScript(以及JavaScript)里没法直接返回多个独立的原始值,但我们可以通过打包成对象或数组的方式,一次性返回两个结果,后续就能分别使用它们了。下面是两种实用的实现方式:

方法1:返回命名对象(推荐)

这种方式可读性最高,因为每个返回值都有明确的名称,后续使用时不用记顺序,代码更易维护。

修改你的代码如下:

public static getTestInfo(input1: string, input2: string): { 
  firstOutput: string; 
  finalResult: ReturnType<typeof class2.callingfunctionxyz> 
} { 
    const firstOutput = class1.callingfunctionabc(input1, input2); 
    const finalResult = class2.callingfunctionxyz(firstOutput); 
    // 将两个结果打包成对象返回
    return { firstOutput, finalResult };
}

使用示例:

// 解构赋值直接获取两个值
const { firstOutput, finalResult } = YourClassName.getTestInfo("yourInput1", "yourInput2");

// 接下来就可以分别使用这两个值做后续处理了
console.log(firstOutput);
console.log(finalResult);

方法2:返回数组

如果觉得对象的写法有点繁琐,也可以用数组来打包结果,不过要注意记住数组中元素的顺序:

public static getTestInfo(input1: string, input2: string): [
  string, 
  ReturnType<typeof class2.callingfunctionxyz>
] { 
    const firstOutput = class1.callingfunctionabc(input1, input2); 
    const finalResult = class2.callingfunctionxyz(firstOutput); 
    // 按顺序放入数组返回
    return [firstOutput, finalResult];
}

使用示例:

// 按数组顺序解构赋值
const [firstOutput, finalResult] = YourClassName.getTestInfo("yourInput1", "yourInput2");

小补充:关于原代码的细节

你原代码里的out firstOutput:string应该是笔误吧?TypeScript中没有这种输出参数的语法,咱们上面的返回多值方案是更符合TS风格的做法哦。

内容的提问来源于stack exchange,提问作者Vinod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:02:32