'TypeScript type for stringified values of a number union type
I am trying to define a TypeScript type that restricts values to the string versions of a set of numbers. Explanation below:
Say I have a union numeric type like so:
const ONE = 1;
const TWO = 2;
type ALLOWED_NUMBER = typeof ONE | typeof TWO;
I would like to also define a companion string type that only allows the stringified versions of these numbers. So that I could do the following:
type ALLOWED_NUMBER_STRING = /* insert solution here :) */
const numericStringA: ALLOWED_NUMBER_STRING = '1'; // no error
const numericStringB: ALLOWED_NUMBER_STRING = '3'; // error
const numericStringC: ALLOWED_NUMBER_STRING = 'foo'; // error
I could manually define this type but it would be great to avoid the redundancy!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
