I have an type defined like this:
export type Thing = "thinga" | "thingb"
Is there a way I can tell if an arbitrary string value that I have is part of that union?
let value1 = "thinga";
let value2 = "otherthing";
console.log("value1: " + value1 <is in> Thing );
console.log("value2: " + value2 <is in> Thing );
Where I want it to be true for value1, but false for value2. The actual use-case is that have an array of strings that I want to filter out if they're not in the definition (and possibly log) and then cast to the correct type.
The wrinkle is that the Thing
type is generated code that gets compiled in with my code and the values can change - so I don't want to write conditional logic in a type guard hardcoded to the value. I don't control the thing that generates the code - otherwise I'm guessing in this case what I want to do would be easy if the type were a string enum instead.
I'm hoping that I can write some kind of typeguard that uses keyof
or something similar? But I can't see how to make it work.
Typescript version is 2.8.1, though upgrading is not a huge issue.
I'm aware of this question: https://stackoverflow.com/a/50085718/924597, but I don't think this is a duplicate because I can't use the answer on that question.