打字稿错误地将元组推断为数组 [英] Typescript inferring Tuple as Array Incorrectly
问题描述
先为我的英语道歉.
我有一个类似 function func(): [string, string[]]
的函数,它返回一个元组.但是,当我实现像
I have a function like function func(): [string, string[]]
which returns a Tuple. However, when I implement the return statement like
var test = ['text', ['foo', 'bar']];
return test;
Typescript 将我的返回类型推断为 (string | string[])[]
而不是 [string, string[]]
.
Typescript inferred my return type as (string | string[])[]
instead of [string, string[]]
.
我是否遗漏了什么,或者我是否需要每次都将返回对象显式转换为元组,例如 return <[string, string[]]>['text', ['foo', 'bar']]代码>.如果是,那不是很烦人吗?
Did I missed something or should I need to cast the return object as Tuple explicitly everytime like return <[string, string[]]>['text', ['foo', 'bar']]
. If yes then isn't it quite annoying?
提供的完整功能如下:
function func(): [string, string[]] {
var test= ['text', ['foo', 'bar']];
return test;
}
错误:类型 '(string | string[])[]' 缺少类型 '[string, string[]]' 的以下属性:0, 1ts(2739)
推荐答案
TS 无法区分,如果你想让 ['text', ['foo', 'bar']]
成为 <一个 href="https://www.typescriptlang.org/docs/handbook/basic-types.html#array" rel="nofollow noreferrer">array 或一个 tuple - 表达式 是一样的!如果没有其他指定,它将默认为 test
变量类型的数组.
TS cannot differentiate, if you want ['text', ['foo', 'bar']]
to be an array or a tuple - the expression is the same! It will default to an array for the test
variable type, if nothing else specified.
如果您想要一个元组,请执行以下操作之一:
If you want a tuple, do one of the following:
- 使用 const 断言
- 给
test
一个显式的元组类型
- use a const assertion
- give
test
an explicit tuple type
function func(): [string, string[]] {
const test = ['text', ['foo', 'bar']];
const test2 = ['text', ['foo', 'bar']] as const;
const test3: [string, string[]] = ['text', ['foo', 'bar']];
// return test; // error, was inferred as array
// return test2; // works
return test3; // works
}
使用 as const
你不必重复你的类型,但你必须用 readonly
修饰符来注释函数返回类型: readonly [string, 只读 [string, string]]
.
With as const
you don't have to repeat your type, but you will have to annotate the function return type with readonly
modifiers: readonly [string, readonly [string, string]]
.
这篇关于打字稿错误地将元组推断为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!