I am exploring ways to create a TypeScript type that restricts values to specific string representations of numbers. Let's dive into the details:
Imagine having a union numeric type defined like this:
const ONE = 1;
const TWO = 2;
type ALLOWED_NUMBER = typeof ONE | typeof TWO;
Now, I want to come up with a string type that only allows the stringified versions of these numbers. Here is what I aim to achieve:
type ALLOWED_NUMBER_STRING = /* seeking a solution for this :) */
const numericStringA: ALLOWED_NUMBER_STRING = '1'; // no error
const numericStringB: ALLOWED_NUMBER_STRING = '3'; // error
const numericStringC: ALLOWED_NUMBER_STRING = 'foo'; // error
While I could manually define this type, my goal is to find an efficient way to avoid redundancy!