typescript - 在 TypeScript 中返回多个值

标签 typescript return-type typechecking

我想在 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/

相关文章:

javascript - Jest : SyntaxError: Unexpected token export

angular - 带有方法的对象上的 Typescript 展开运算符

javascript - 如何返回数组/值作为可以在模板中使用的光标?

c - Floodfill 算法 C - 返回双数组?

c - 以字符串为返回类型的函数

android - 为什么 Ionic 键盘事件没有触发?

javascript - 管道放置下划线底部字母 Angular

haskell - GHC/GHCi 意外接受的代码

wolfram-mathematica - 在具有保留参数的函数中键入检查符号的快速方法

c++ - 如果模板参数无效,请在编译时检查