gpt4 book ai didi

typescript - 在 TypeScript 中返回多个值

转载 作者:行者123 更新时间:2023-12-05 09:34:26 24 4
gpt4 key购买 nike

我想在 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 Playground Link

关于typescript - 在 TypeScript 中返回多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66661166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com