typed-tuple
A function that returns a typed tuple from an array of literals.
Based on this excellent gist by Joe Calzaretta.
Install
npm install typed-tuple --save
then...
;
The Problem
Take the following string union type.
;
This is great for restricting a variable to one of four suits. But what if you also want a list of all possible suits?
; ;
The problem with this is ALL_SUITS
is actually typed as Suit[]
. But Suit[]
can also mean any of the following values []
, ['hearts']
, ['hearts', 'hearts']
, etc. We've also had to repeat ourselves.
We could explicitly type it like this:
; ;
This gets the typing right, but we've made our code even less DRY - ack!
The Solution
We can use typed-tuple to reduce all this code:
; ; ;
Hooray! At last...
ALL_SUITS
is the correct type of['hearts', 'diamonds', 'spades', 'clubs']
Suit
is the correct type of'hearts' | 'diamonds' | 'spades' | 'clubs'
- And our code is now nice and DRY