Typescript type for fixed size arrays
This package contains type definitions for arrays of fixed length in Typescript. The size of the arrays is checked at compile time.
It could be useful in a variety of cases. For example, checking if the correct number of configuration options are passed to a function.
At the moment, we can use only immutable arrays since arithmetic operations over numeric literals have not been implemented in Typescript, yet. Workarounds without using numeric literals (e.g. define numbers by recursion) look too hacky and impractical, but any suggestion is welcome!
Requirements
Typescript >=2.8
Getting started
Install package
$ npm i fixed-size-array
Use type definitions in your Typescript project
; let d: FixedSizeArray<2 string>;
Bugs and issues
Apparently, the package works as expected for many practical cases. Howerver, I do not know if its behavior is always correct. Feel free to open an issue on github if you meet something odd.
Example
; // define a string array of length 2let d: FixedSizeArray<2 string>; d = 'a' 'b'; // okd0 = 'a2'; // okd2 = 'c2'; // type errord = 'a'; // type errord = 'a' 'b' 'c'; // type errord = 'a' true; // type error d; // type error // define an empty array of strings let e: FixedSizeArray<0 string>; e = ; // oke = as string; // type error: e has type never[] // with objects does not work, as wantedlet o: FixedSizeArray<2 string>;o = length: 2 0: 'a' 1: 'b' // type error // missing array methods o = length: 2 0: 'a' 1: 'b' 'l': 'c' // type error // spurious property name
Current problems and limitations
Access to array elements through their indexes will result in a type error.
let d: FixedSizeArray<2 string>; d = 'a' 'b'; // okd0 = 'a2'; // okd1 = 'b2'; // type error, but it is wrong!d2 = 'c2'; // type error
Other more complex cases.
interface Fun<N extends number M extends number> a: FixedSizeArray<N number>: FixedSizeArray<M number>;let f: Fun<23>; // type error { return 123} // ok { return 123} //ok;
Credits
We use the same trick to assign a numeric literal to length as it was done in TS 2.7 for tuples of fixed size.
Type definition had been simplified as suggested here by @tycho01.