Suppose I have such a String Literal:

type Style = 'classic' | 'modern' | 'future'; 

From somewhere outside (for example, via an Ajax request) I received a string with an indication of the style:

 const sAjaxStyle: string; 

How to convert sAjaxStyle to Style with default value (if there is no corresponding value in Style ), for example, 'classic' ? Do not write me a function like:

 function convertStringToStyle(s: string): Style { if (s == 'modern') return 'modern' else if (s=='future') return 'future' else return 'classic'; } 

and constantly expand it? Should there be a way to sort through "automatically"?

    2 answers 2

    Security programming requires something like writing. Well, you can slightly reduce the number of string literals in the code:

     function convertStringToStyle(s: string): Style { if (s == 'modern' || s == 'future' || s == 'classic') return s; else throw 'Wrong style value: ' + s; } 

    If you think that there can be no mistakes on the other side, or in this particular place you decide to follow the principle of GIGO (Garbage In - Garbage Out) - then you can use a cast like:

     const style = <Style>sAjaxStyle; 
    • I don't want to constantly extend the convertStringToStyle function after extending the Style. Is there really no way to understand that the string satisfies a string literal? Well, something like: if (stringValidLiteral ('modern', Style)) {...} - Pit

    I think I found a way - you need to use the enum of the form:

     enum Style { classic='classic', modern='modern', future='future' } 

    A bit redundant, but it makes it easy to write a universal conversion function:

     function convertStringToStyle(s: string): Style { const res = Style[s]; if (!s) res = Style.classic; return res; } 

    If you want to display a style in a string, then it is also simple:

     var style: Style = Style.classic; // Для примера var s: string = style.toString(); 
    • Sorry, wrong. Instead of if (! S) res = Style.classic; should be if (! res) res = Style.classic; - Pit