Note: I\'m new to typescript. Prior to posting I read the docs regarding advance types and type guards. In addition I also read several related S.O. question (e.g. user defi
The best way to do this is to derive the type Format
from a value like an array which contains all of the Format
literals. There are a number of ways to do this. I will show the easiest way assuming you are using TS3.4+:
const formats = ['JSON', 'CSV', 'XML'] as const;
type Format = typeof formats[number];
You can verify that Format
is the same as before. Now, armed with an array, you can use it to build a type guard:
function isFormat(x: string): x is Format {
// widen formats to string[] so indexOf(x) works
return (formats as readonly string[]).indexOf(x) >= 0;
}
That should work as expected and not be too verbose (or at least it doesn't repeat string literals anywhere). Hope that helps; good luck!