TypeScript 转换数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12792695/
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-09-11 00:51:18  来源:igfitidea点击:

TypeScript casting arrays

castingtypescript

提问by Adam Tegen

I'm trying to use a wrapper for a library that wants an Array as an input parameter.

我正在尝试为需要数组作为输入参数的库使用包装器。

I tried casting the Array, but I get an error: Cannot convert 'any[]' to 'Array'

我尝试投射数组,但出现错误:无法将 'any[]' 转换为 'Array'

Is there a way to make this work?

有没有办法使这项工作?

var rows = new Array(10);
var rows2 = <Array>rows; //<--- Cannot convert 'any[]' to 'Array'

回答by shadeglare

There are 4 possible conversion methods in TypeScript for arrays:

TypeScript 中有 4 种可能的数组转换方法:

let x = []; //any[]

let y1 = x as number[];
let z1 = x as Array<number>;
let y2 = <number[]>x;
let z2 = <Array<number>>x;

The asoperator's mostly designed for *.tsxfiles to avoid the syntax ambiguity.

as运营商的主要设计*.tsx文件,以避免语法歧义。

回答by Tsvetomir Nikolov

I think the right syntax is:

我认为正确的语法是:

var rows2 = <Array<any>>rows;

That's how you cast to interface Array<T>

你就是这样投的 interface Array<T>

回答by Ryan Cavanaugh

I think this is just a bug - can you log an issue on the CodePlex site?

我认为这只是一个错误 - 您可以在 CodePlex 站点上记录问题吗?

As a workaround, you can write <Array><any>rows;

作为一种解决方法,您可以编写<Array><any>rows;

回答by Jayant Varshney

A simple solution for all types

适用于所有类型的简单解决方案

const myArray = <MyType[]>value;