debugtypescriptCritical
How to declare a fixed length array in TypeScript?
Viewed 0 times
arrayfixedtypescripthowdeclarelength
Problem
When you make a type declaration for an array like this:
it will let you make an array with arbitrary length. However, if you want an array containing numbers with a specific length, e.g. 3 for x, y, z components. Can you make a type with for a fixed length array, something like this?
position: Array;it will let you make an array with arbitrary length. However, if you want an array containing numbers with a specific length, e.g. 3 for x, y, z components. Can you make a type with for a fixed length array, something like this?
position: ArraySolution
The JavaScript array has a constructor that accepts the length of the array:
However, this is just the initial size, there's no restriction on changing that:
TypeScript has tuple types which let you define an array with a specific length and types:
let arr = new Array(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 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]'Code Snippets
let arr = new Array<number>(3);
console.log(arr); // [undefined × 3]arr.push(5);
console.log(arr); // [undefined × 3, 5]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]'Context
Stack Overflow Q#41139763, score: 368
Revisions (0)
No revisions yet.