Looking at Is it possible to restrict number to a certain range I found the type for creating Ranges and Enumerates.
Looking at What is the type of an enum in Typescript? I found a type definition for passing Enums as values to functions.
Now: I'm writing a lil UI/UX library here at prudencss@github, my hobby project. Whilst doing so, playing around and trying to do things properly ... I was trying to introduce the following mechanism:
I wanted to create enums like:
export enum EInputInteractionState {
Default = 0,
Hover = 1,
Focus = 2,
Active = 4,
Selected = 8,
}
Now, it would be possible and sometimes useful to have combinatoric states of the defined states as well, for example some list element could be:
- hovered
- selected
at the same time.
In order to be able to save all that data in one var/number, I define the initial keys/values as
v = 0, 2^n ... (== 0, 1, 2, 4, 8, 16, ...)
This would allow me to save every permutated combinatoric state as a number that is the sum of it's active defined states ... that number would always fill the gaps in between the quadratic row of numbers .... So basically though I define 5 states (= default state, plus 4 combinatoric states) in EInputInteractionState and define them asv = 0, 2^n
, the overall combinatorically possible values would be the row symbolising the gaussian sum ofv = 0, 1, 2, 3, ... n, ... (n * 2 - 1)
= (n * (n + 1) /2)`.
Using the knowledge so far I do:
export const gaussianSum = <T extends Enum<T>>(E: T): number => {
let length = Object.keys(E).filter(v => isNaN(v as unknown)).length;
return length * (length + 1) / 2 + 1;
}
Now I wanted to finally and simply put a Prop into my React Components IProps of:
const permutationCount: number = gaussianSum(EInputInteractionState);
interface IProps {
icon?: TIcon | TIcon[]
state?: Enumerate<typeof permutationCount>,
}
However, if I simply put a concrete number the Enumarte type works quite well, but using this scenario I get TS2589 "Type instantiation is excessively deep and possibly infinite."
Is there a way to solve this issue???
Edit: typescript playground here: playground