The output method of defining type functions based on conditions in TypeScript
P粉764836448
P粉764836448 2023-08-14 18:18:08
0
1
403
<p>I'm trying to define an output type for my function and I want to have it between the <code>string</code> and <code>number</code> types based on the <code>toNumberIfNeeded</code> flag Set conditions between, assuming that if <code>toNumberIfNeeded</code> is true, this function will return a numeric type, otherwise it will return a string type. What should I do? </p> <pre class="brush:php;toolbar:false;">interface Options { uppercase?: boolean; filterSpecialChars?: boolean; toNumberIfNeeded?: boolean; } export const textTransformer = (text: string, options?: Options) => { const { uppercase, filterSpecialChars, toNumberIfNeeded} = options || {}; //My processing logic code return toNumberIfNeeded ? parseInt(text) : text; }</pre> <p>Expected example: </p> <pre class="brush:php;toolbar:false;">textTransformer('hello'); // Return string type textTransformer('123', { toNumberIfNeeded: true }); // Return numeric type</pre>
P粉764836448
P粉764836448

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!