Trying to develop a class that allows for both hex and rgb color options has presented a challenge. When using hex values, the generic is forced to be a literal number instead of just a number. For example, specifying 0xff00ff
results in it being defined as 16711935
, which creates an issue when attempting to redefine it.
This limitation leads to a TypeScript error when setting the color to 0xff0000
:
Type '16711680' is not assignable to type '16711935'
An example demonstrating this problem can be found on this playground
To address this issue, forcing a cast to the class like so: new MyClass<number>({...})
, resolves the problem. However, finding a way to avoid the need for forced literals would be preferable over requiring users to directly cast the type during class instantiation.