I am trying to define type for output of my function, I want to set condition between string and number types depend on toNumberIfNeeded flag, suppose if toNumberIfNeeded is true then this function will return an number type and vice versa return string type. How I can do it?
interface Options {
uppercase?: boolean;
filterSpecialChars?: boolean;
toNumberIfNeeded?: boolean;
}
export const textTransformer = (text: string, options?: Options) => {
const { uppercase, filterSpecialChars, toNumberIfNeeded} = options || {};
// my handle logics code
return toNumberIfNeeded ? parseInt(text) : text;
}
Example what I expected:
textTransformer('hello'); // return string type
textTransformer('123', { toNumberIfNeeded: true }); // return number type
You could refactor textTransformer() to accept a generic parameter and use a conditional type to check whether toNumberIfNeeded is true or false. I don't think TypeScript is able to narrow down the return value automatically. You'll have to use Type Assertion for that otherwise the return type is inferred as string | number.
interface Options {
uppercase: boolean;
filterSpecialChars: boolean;
toNumberIfNeeded: boolean;
}
export const textTransformer = <T extends Options>(
text: string,
options?: T
): T["toNumberIfNeeded"] extends true ? number : string => {
const {uppercase, filterSpecialChars, toNumberIfNeeded} =
options || {};
// my handle logics code
return (toNumberIfNeeded ? parseInt(text) : text) as ReturnType<
typeof textTransformer
>;
};
textTransformer("hello"); // inferred as string
textTransformer("123", {
toNumberIfNeeded: true,
uppercase: false,
filterSpecialChars: false
}); // inferred as number
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With