Typescript: User-Defined type guards for literal types? Typescript: User-Defined type guards for literal types? typescript typescript

Typescript: User-Defined type guards for literal types?


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!