P粉8785424592023-08-15 13:04:14
You can refactor the textTransformer()
method to accept a generic parameter and use a conditional type to check whether toNumberIfNeeded
is true
or false
. 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 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 || {}; // 我的处理逻辑代码 return (toNumberIfNeeded ? parseInt(text) : text) as ReturnType< typeof textTransformer >; }; textTransformer("hello"); // 推断为 string textTransformer("123", { toNumberIfNeeded: true, uppercase: false, filterSpecialChars: false }); // 推断为 number