Hacker News new | ask | show | jobs
by brundolf 1733 days ago
That is an annoying thing I've run into as well

My solution is to make a type guard:

  function isExample(val: string): val is Example {
    return (ALL as string[]).includes(val)
  }
I've also found there's no need to even create an object by the way; you can just create a string array and then use string literals directly in your code. Also, TS is smart enough to still give you intelligent autocomplete.

(you don't even need the array unless you need to iterate over the items at runtime like above; in other situations, you can often just make a type and nothing else)

1 comments

Oh that’s very clever. Makes me wish javascript/Typescript had macros so I could define this all in a single call.