Home > Enterprise >  Simplify constant variables mapped to union type
Simplify constant variables mapped to union type

Time:12-22

I'm defining a union type with some constant variables:

type Token = ' ' | '-';
const TOKEN_PLUS: Token = ' ';
const TOKEN_MINUS: Token = '-';

I feel that somehow it can be simplified. I don't like having to repeat the ' ' and '-' (could be many more).

Any ideas on how to simplify?

CodePudding user response:

There's a couple of possibilities here. Usually, I will not export const representations of members of a union type, since the typechecker and auto-complete will let me use the strings as values instead, if you have a solid reason to keep things as they are I would suggest inverting the code.

const TOKEN_PLUS = ' ';
const TOKEN_MINUS = '-';

type Token = typeof TOKEN_PLUS | typeof TOKEN_MINUS;

const test: Token = TOKEN_PLUS // okay
const test2: Token = ' ' // okay
const fail: Token = '$' // error

Alternatively, you could consider an enum, which would combine your consts and type with just the enum, but you would not be able to use a string literal to initialize a value

enum Token {
  Plus = ' ',
  Minus = '-'
}

const test3 = Token.Plus // okay
const test4: Token = ' ' // not okay
  • Related