Last active
May 11, 2020 00:24
-
-
Save fvilante/1cbca6f2bc1b853b33564f112fae49b5 to your computer and use it in GitHub Desktop.
TS Tuple - manage a defined collection of tuples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: