天道酬勤,学无止境

fixed-length-array

如何在TypeScript中声明固定长度的数组(How to declare a Fixed length Array in TypeScript)

问题 冒着冒我缺乏对TypeScript类型的知识的风险-我有以下问题。 当您为这样的数组进行类型声明时... position: Array<number>; ...它将让您制作一个具有任意长度的数组。 但是,如果您想要一个包含特定长度的数字的数组,例如x,y,z分量为3,可以为固定长度的数组创建类型,是这样吗? position: Array<3> 任何帮助或澄清表示赞赏! 回答1 javascript数组具有一个接受数组长度的构造函数: let arr = new Array<number>(3); console.log(arr); // [undefined × 3] 但是,这只是初始大小,更改此大小没有限制: arr.push(5); console.log(arr); // [undefined × 3, 5] Typescript具有元组类型,可让您定义具有特定长度和类型的数组: 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

2021-04-15 22:37:48    分类:技术分享    typescript   types   fixed-length-array

How to declare a Fixed length Array in 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>; ...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> Any help or clarification appreciated!

2021-03-30 16:41:47    分类:问答    typescript   types   fixed-length-array