Return TypeScript 中的多个值
Return multiple values in TypeScript
我想在 TypeScript 函数的 return 语句中 return 多个值。在 JavaScript 中执行此操作的标准方法是 return 一个包含值 (source) 的数组,但是,由于我想要 return 的值具有不同的类型,编译时出现错误:
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));
~~~~~~~~~
如何操作?
感谢您的帮助。
您需要指定您的 return 是 tuple type,否则它将被解释为 Array<string | number>
。
function fun(): [string, number] {
return ['hello', 1];
}
我们说 returned 值是一个特定的数组,其中第一个元素的类型为 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`
return 类型被推断为 (string | number)[]
。要推断为元组,您可以使用 const 断言。 TS Documentation for const assertion
function fun() {
return ['hello', 1] as const;
}
let [a, b] = fun();
console.log(a.substring(1));
我想在 TypeScript 函数的 return 语句中 return 多个值。在 JavaScript 中执行此操作的标准方法是 return 一个包含值 (source) 的数组,但是,由于我想要 return 的值具有不同的类型,编译时出现错误:
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));
~~~~~~~~~
如何操作?
感谢您的帮助。
您需要指定您的 return 是 tuple type,否则它将被解释为 Array<string | number>
。
function fun(): [string, number] {
return ['hello', 1];
}
我们说 returned 值是一个特定的数组,其中第一个元素的类型为 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`
return 类型被推断为 (string | number)[]
。要推断为元组,您可以使用 const 断言。 TS Documentation for const assertion
function fun() {
return ['hello', 1] as const;
}
let [a, b] = fun();
console.log(a.substring(1));