如何在 TypeScript 中声明一个固定长度的数组 [英] How to declare a Fixed length Array in TypeScript
问题描述
冒着证明我对 TypeScript 类型缺乏了解的风险 - 我有以下问题.
At the risk of demonstrating my lack of knowledge surrounding TypeScript types - I have the following question.
当你为这样的数组进行类型声明时...
When you make a type declaration for an array like this...
position: Array<number>;
...它会让你制作一个任意长度的数组.但是,如果您想要一个包含特定长度数字的数组,即 x,y,z 分量为 3,您可以为固定长度数组创建一个类型,例如这样吗?
...it will let you make an array with arbitrary length. However, if you want an array containing numbers with a specific length i.e. 3 for x,y,z components can you make a type with for a fixed length array, something like this?
position: Array<3>
感谢任何帮助或澄清!
推荐答案
javascript 数组有一个接受数组长度的构造函数:
The javascript array has a constructor that accepts the length of the array:
let arr = new Array<number>(3);
console.log(arr); // [undefined × 3]
然而,这只是初始大小,改变它没有限制:
However, this is just the initial size, there's no restriction on changing that:
arr.push(5);
console.log(arr); // [undefined × 3, 5]
Typescript 具有 元组类型,可让您定义数组具有特定长度和类型:
Typescript has tuple types which let you define an array with a specific length and types:
let arr: [number, number, number];
arr = [1, 2, 3]; // ok
arr = [1, 2]; // Type '[number, number]' is not assignable to type '[number, number, number]'
arr = [1, 2, "3"]; // Type '[number, number, string]' is not assignable to type '[number, number, number]'
这篇关于如何在 TypeScript 中声明一个固定长度的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!