Typescript: User-Defined type guards for literal types?

前端 未结 1 1216
野的像风
野的像风 2020-12-21 02:30

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

相关标签:
1条回答
  • 2020-12-21 02:54

    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!

    0 讨论(0)
提交回复
热议问题