Javascript 如何在 TypeScript 2 中转换为数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39649994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:46:31  来源:igfitidea点击:

How to cast to array in TypeScript 2?

javascripttypescriptcastingtypescript2.0

提问by FlavorScape

I had some code that cast an object to type array (so I could use array functions on the object without compile errors).

我有一些代码将对象转换为数组类型(因此我可以在对象上使用数组函数而不会出现编译错误)。

    var n = (result.data['value'] as []).map( (a)=>{
      //..
    });

But on upgrade to ts2, I get:

但是在升级到 ts2 时,我得到:

error TS1122: A tuple type element list cannot be empty.

错误 TS1122:元组类型元素列表不能为空。

Which is actually a syntax error, claiming you forgot a comma or value. So, how do I modify this cast to work correctly?

这实际上是一个语法错误,声称您忘记了逗号或值。那么,如何修改此演员表以使其正常工作?

I tried as [IMyType]and it worked, but I'd prefer not to specify type since I only need the array.prototypefunctions here... also, I don't think that's how you actually do it.

我试过了as [IMyType],它奏效了,但我不想指定类型,因为我只需要array.prototype这里的函数......而且,我认为这不是你实际这样做的方式。

回答by Nitzan Tomer

For some reason the compiler thinks that result.data['value']is a tupleand not an array.

出于某种原因,编译器认为这result.data['value']是一个元组而不是一个数组。

You can cast it like this:

你可以这样投射:

result.data['value'] as any[]

Which should tell the compiler that it's an array, or:

这应该告诉编译器它是一个数组,或者:

result.data['value'] as Array<any>


If your array has only items of type IMyTypethen simply:

如果您的数组只有类型的项目,IMyType那么只需:

result.data['value'] as IMyType[]

However, if your array contains items of different types then it's either a any[]or a tuple, for example:

但是,如果您的数组包含不同类型的项目,那么它要么是any[]一个元组,要么是一个元组,例如:

result.data['value'] as [IMyType, string, string]

In any case, in the compiled js it will be an array, but tuples let you define a fixed length arrays with specific types.

在任何情况下,在编译后的 js 中它将是一个数组,但是元组允许您定义具有特定类型的固定长度数组。

回答by chrisbajorin

You're not casting to an array.

你没有投射到一个数组。

[string]is a tuple with a single element string.

[string]是一个具有单个元素的元组string

[string, string]is a tuple with two elements, stringand string.

[string, string]是一个有两个元素的元组,stringstring

[]is a tuple with zero elements.

[]是一个元素为零的元组。

The syntax for an array of strings is string[]

字符串数组的语法是 string[]

What you likely want is result.data['value'] as any[].

您可能想要的是result.data['value'] as any[].

回答by Gorka Hernandez

Alternatively to the previous cast syntax options mentioned above, you can also do the following:

除了上面提到的先前的强制转换语法选项,您还可以执行以下操作:

var n = (<SampleType[]>result.data['value']).map((a) => {
    //..
});