【问题标题】:How to set a tuple in TypeScript?如何在 TypeScript 中设置元组?
【发布时间】:2019-09-28 04:00:14
【问题描述】:

我有以下注释,在 typescript 3.5.3 版本中定义元组时收到错误消息。 可能是什么问题?

type Test = [string, number];
const xxx: Test = () => ['hello', 10];

我得到错误: Type '() => (string | number)[]' is not assignable to type '[string, number]'.

【问题讨论】:

  • 你里面为什么有() => ?那是 lambda 语法。您正在尝试将函数分配给元组类型的变量。
  • 我想要一个将一些数据作为元组返回的函数....有可能吗?
  • 但是你说Test 是一个元组,而不是一个返回元组的函数,并且你有xxx 作为类型Test。你想让xxx 成为返回元组还是元组的函数?
  • 是的,请以什么方式
  • 再一次,您希望 Test 是一个返回元组的函数类型,还是返回元组?哪一个?

标签: typescript


【解决方案1】:

如果您想将xxx 设置为输入Test,请执行以下操作:

type Test = [string, number];

const xxx: Test = ['hello', 10];

const xxx: Test = getTest();
getTest(): Test { return ['hello', 10]; }

更新

xxx 设置为返回Test 的函数看起来更像这样:

type Test = () => [string, number];

const test: Test = () => ['hello', 10];

如果您希望 Test 只是元组,但 xxx 是返回元组的函数,您也可以这样做:

type Test = [string, number];

const xxx: () => Test = getTest;

getTest(): Test { return ['hello', 10]; }

【讨论】:

  • 听起来 OP 实际上想要type Test = () => [string, number]
猜你喜欢
  • 2017-08-30
  • 2021-09-08
  • 2021-04-04
  • 1970-01-01
  • 2023-01-30
  • 2021-02-24
  • 2017-05-15
  • 2014-02-13
  • 1970-01-01
相关资源
最近更新 更多