In TypeScript, is it possible to apply an arithmetic mapping function to a number
literal type?
Minimum reproducible contrived (but illustrative) case:
type ternary =
| 0
| 1
| 2
;
/**
* DESIRED: Offset number literal type 'ternary' by 1.
*
* Pseudo-notation:
*
* type ternaryR = ternary + 1;
*/
// manual typing so code transpiles
type ternaryR =
| 1
| 2
| 3
;
const buffer: [
number, // metadata
[number, number],
[number, number],
[number, number],
] = [
10001337,
[11, 12],
[21, 22],
[31, 32],
]
function safeIncrement(
i: ternaryR,
) {
const iNext = i + 1;
if (
Number.isInteger(iNext)
&& iNext > 0
&& iNext < 4
)
return i + 1 as ternaryR;
else
throw new RangeError("");
}
for (
let i: ternaryR = 1;
i < 4;
i = safeIncrement(i);
)
// trivial example
buffer[i][0] = buffer[i][1] // OK
From doing some research, I suspect there is a possible solution using string
literals to infer number
to string
or vice versa (as I’ve seen @jcalz propose elsewhere) and then using string manipulation, but the inherent limitation with string manipulation is that I’d have to hard-code some logical grammar (incrementing 8
gives 9
, which incremented gives 10
) that could become unwieldy.
Any suggestions from those more knowledgeable / type-adept than me?