The output method of defining type functions based on conditions in TypeScript
P粉764836448
2023-08-14 18:18:08
<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>
You can refactor the
textTransformer()
method to accept a generic parameter and use a conditional type to check whethertoNumberIfNeeded
istrue
orfalse
. I don't think TypeScript can automatically narrow the type of the return value. You must use type assertions, otherwise the return type will be inferred asstring | number
.