Skip to content

Instantly share code, notes, and snippets.

@fvilante
Last active May 11, 2020 00:24
Show Gist options
  • Save fvilante/1cbca6f2bc1b853b33564f112fae49b5 to your computer and use it in GitHub Desktop.
Save fvilante/1cbca6f2bc1b853b33564f112fae49b5 to your computer and use it in GitHub Desktop.
TS Tuple - manage a defined collection of tuples
interface FixedArray<Size extends number, A> extends ArrayLike<A> { length: Size }
type MyTriple = FixedArray<3,number>
const ok_case: MyTriple = [1,2,3] as const // ok !
const erro_case1: MyTriple = [1,2] as const // fewer elements
const erro_case2: MyTriple = [1,2,3,4] as const // many elements
const erro_case3: MyTriple = [1,2,3] // not constant in static-time
const erro_case4: MyTriple = [] as const // well, it's empty my son!
const f = <A extends FixedArray<1|2|3, B>,B>(n_tuple: A) => {
const size = n_tuple.length
switch (size) {
case 1: break;
case 2: break;
case 3: break;
}
}
f(['X'] as const)
f(['X',0] as const)
f(['X',0,0] as const)
f(['X',0,0,1] as const) // Type '4' is not assignable to type '1 | 2 | 3'.ts(2345)
@fvilante
Copy link
Author

fvilante commented May 11, 2020

Note: define MyTriple as below has the same effect, with the benefit of the sintax sugar of not being required to use the termination 'as const' when assign a tuple instance:

type MyTriple_ = readonly [number] | readonly [number, number] | readonly [number, number, number]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment