用于数字联合类型的字符串化值的 TypeScript 类型
TypeScript type for stringified values of a number union type
我正在尝试定义一个 TypeScript 类型,它将值限制为一组数字的字符串版本。解释如下:
假设我有一个像这样的联合数字类型:
const ONE = 1;
const TWO = 2;
type ALLOWED_NUMBER = typeof ONE | typeof TWO;
我还想定义一个伴随字符串类型,它只允许这些数字的字符串化版本。这样我就可以执行以下操作:
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
我可以手动定义这种类型,但如果能避免冗余就好了!
您正在寻找 template literal types:
const ONE = 1;
const TWO = 2;
type ALLOWED_NUMBER = typeof ONE | typeof TWO;
type ALLOWED_NUMBER_STRING = `${ALLOWED_NUMBER}`;
const numericStringA: ALLOWED_NUMBER_STRING = '1';
const numericStringB: ALLOWED_NUMBER_STRING = '3'; /*
^^^^^^^^^^^^^^
Type '"3"' is not assignable to type '"1" | "2"'.(2322) */
const numericStringC: ALLOWED_NUMBER_STRING = 'foo'; /*
^^^^^^^^^^^^^^
Type '"foo"' is not assignable to type '"1" | "2"'.(2322) */
而且,对于一组数字,您可以通过这种方式使其更干燥:
const allowedNumbers = [1, 2, 3] as const;
type AllowedNumber = typeof allowedNumbers[number]; // 1 | 2 | 3
type AllowedNumberStr = `${AllowedNumber}`; // "1" | "2" | "3"
我正在尝试定义一个 TypeScript 类型,它将值限制为一组数字的字符串版本。解释如下:
假设我有一个像这样的联合数字类型:
const ONE = 1;
const TWO = 2;
type ALLOWED_NUMBER = typeof ONE | typeof TWO;
我还想定义一个伴随字符串类型,它只允许这些数字的字符串化版本。这样我就可以执行以下操作:
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
我可以手动定义这种类型,但如果能避免冗余就好了!
您正在寻找 template literal types:
const ONE = 1;
const TWO = 2;
type ALLOWED_NUMBER = typeof ONE | typeof TWO;
type ALLOWED_NUMBER_STRING = `${ALLOWED_NUMBER}`;
const numericStringA: ALLOWED_NUMBER_STRING = '1';
const numericStringB: ALLOWED_NUMBER_STRING = '3'; /*
^^^^^^^^^^^^^^
Type '"3"' is not assignable to type '"1" | "2"'.(2322) */
const numericStringC: ALLOWED_NUMBER_STRING = 'foo'; /*
^^^^^^^^^^^^^^
Type '"foo"' is not assignable to type '"1" | "2"'.(2322) */
而且,对于一组数字,您可以通过这种方式使其更干燥:
const allowedNumbers = [1, 2, 3] as const;
type AllowedNumber = typeof allowedNumbers[number]; // 1 | 2 | 3
type AllowedNumberStr = `${AllowedNumber}`; // "1" | "2" | "3"