1

I am coding a crude abstract syntax tree based on user input. In my AST type, I want to have type literals for valid operators. How do I convert the user input (strings) to string type literals in a safe manner? Consider the snippet below.

type operator = '==' | '!=';

function isOperator(raw: string): raw is operator {
    return ['==', '!='].indexOf(raw) !== -1
}

const parseOperator = (raw: string) => {
    if (isOperator(raw)) {
        return raw
    } else {
        throw new Error('Invalid input')
    }
}

const indata: string[] = ['!=', '!=', '==','a']
const data: operator[] = indata.map(parseOperator)

In the code, I have duplicated the valid operators (once in the type definition, and later in the parsing logic). That seems to be a bad way to structure code, since updating the operator type means I have to update hard coded arrays in other places.

What is the idiosyncratic typescript way to do this assertion?

ps. I realize this question: Ways to get string literal type of array values without enum overhead is realated. The answerthere seems kind-of-hackish to me though. If that is the best poossible solution - please explain why it is a good coding style.

LudvigH
  • 3,662
  • 5
  • 31
  • 49

0 Answers0