TypeScript 数组剩余赋值的类型推断不正确,无法添加注解,

xam8gpfp  于 7个月前  发布在  TypeScript
关注(0)|答案(5)|浏览(93)

TypeScript版本: 2.7.1-insiders.20180127
搜索词: array destructuring rest assignment
代码:

// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.
const [stringA, ...numbers] = ['string', 1, 2];
// const [stringA, ...numbers] = <[string, number, number]>['string', 1, 2];
// const [stringA, ...numbers]: [string, number[]] = ['string', 1, 2];
// const [stringA, ...numbers]: [string, [number, number]] = ['string', 1, 2];

预期行为: 期望 numbers 的类型为 number[],而不是 (string | number)[]。TS也不允许将其标记为元组。
实际行为: const numbers: (string | number)[]
**Playground链接:**http://www.typescriptlang.org/play/index.html#src=const%20%5BstringA%2C%20...numbers%5D%20%3D%20%5B'string'%2C%201%2C%202%5D%3B%0A%2F%2F%20const%20%5BstringA%2C%20...numbers%5D%20%3D%20%3C%5Bstring%2C%20number%2C%20number%5D%3E%5B'string'%2C%201%2C%202%5D%3B%0A%2F%2F%20const%20%5BstringA%2C%20...numbers%5D%3A%20%5Bstring%2C%20number%5B%5D%5D%20%3D%20%5B'string'%2C%201%2C%202%5D%3B%0A%2F%2F%20const%20%5BstringA%2C%20...numbers%5D%3A%20%5Bstring%2C%20%5Bnumber%2C%20number%5D%5D%20%3D%20%5B'string'%2C%201%2C%202%5D%;
相关问题:

xpszyzbs

xpszyzbs1#

正确的类型应该是 const [stringA, ...numbers]: [string, number, number] ,而 numbers 应该被正确推断。这是一个我们应该修复的bug。

w1jd8yoj

w1jd8yoj2#

我也曾遇到过这个关于重载函数的问题。

$x_1a^0b^1x$

o4hqfura

o4hqfura3#

在开放帖子中的问题已在typescript@next中修复,甚至可能在3.0.0-rc中修复。
numbers现在类型为number[]

yvfmudvl

yvfmudvl4#

重复:#3369。在没有显式类型注解的情况下,元组类型不会被推断。你可以在#16656中找到相关讨论。

ahy6op9u

ahy6op9u5#

元组类型在没有显式类型注解的情况下不会被推断
@mhegazy 那么如何将 numbers 的剩余赋值注解为元组?我相信我在最后一行尝试过这个:

const [stringA, ...numbers]: [string, [number, number]] = ['string', 1, 2];

相关问题