fixed-size-array
TypeScript icon, indicating that this package has built-in type declarations

0.1.1 • Public • Published

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

import { FixedSizeArray } from 'fixed-size-array';
 
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

import { FixedSizeArray } from 'fixed-size-array';
 
// define a string array of length 2
let d: FixedSizeArray<2, string>;
 
= ['a', 'b']; // ok
d[0] = 'a2'; // ok
d[2] = 'c2'; // type error
= ['a']; // type error
= ['a', 'b', 'c']; // type error
= ['a', true]; // type error
 
d.push('d'); // type error       
 
// define an empty array of strings            
let e: FixedSizeArray<0, string>;
 
= []; // ok
= [] as string[]; // type error: e has type never[]
 
// with objects does not work, as wanted
let o: FixedSizeArray<2, string>;
= {
  length: 2,
  0: 'a',
  1: 'b'
  // type error
  // missing array methods
}
 
= {
  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>;
 
= ['a', 'b']; // ok
d[0] = 'a2'; // ok
d[1] = 'b2'; // type error, but it is wrong!
d[2] = '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<2,3>;
 
// type error
f = function(v: [number, number]) {
  return [1,2,3]
}
 
// ok
f = function(v: FixedSizeArray<2, number>) {
  return [1,2,3]
}
 
//ok
f([1,2]);

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.

Readme

Keywords

Package Sidebar

Install

npm i fixed-size-array

Weekly Downloads

1,105

Version

0.1.1

License

MIT

Unpacked Size

4.59 kB

Total Files

4

Last publish

Collaborators

  • mstn