我想在 TypeScript 函数的返回语句中返回多个值。在 JavaScript 中执行此操作的标准方法是返回包含值的数组 ( source ),但是,由于我要返回的值属于不同类型,因此在编译期间出现错误:
function fun() {
return ['hello', 1];
}
let [a, b] = fun();
console.log(a.substring(1));
错误:
test.ts:6:15 - error TS2339: Property 'substring' does not exist on type 'string | number'.
Property 'substring' does not exist on type 'number'.
6 console.log(a.substring(1));
~~~~~~~~~
如何做到这一点?
感谢您的帮助。
最佳答案
您需要指定您的返回是 tuple type , 否则它将被解释为 Array<string | number>
.
function fun(): [string, number] {
return ['hello', 1];
}
我们说返回值是一个特定的数组,其中第一个元素是类型 string
第二个是类型 number
.这允许在 destructuring 时分配正确的类型.
let [a, b] = fun();
console.log(a.substring(1)); // logs "ello" - a has type `string`
console.log(b.toPrecision(3)); // logs "1.00" - b has type `number`
关于typescript - 在 TypeScript 中返回多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66661166/