打字稿错误地推论元组为数组 [英] Typescript inferring Tuple as Array Incorrectly
问题描述
先为我的英语道歉.
我有一个像 function func():[string,string []]
这样的函数,它返回一个元组.但是,当我实现return语句
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)
推荐答案
如果您想将 ['text',['foo','bar']]
用作
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
}
使用作为常量
,您不必重复输入类型,但是必须使用 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屋!