Maison > Questions et réponses > le corps du texte
P粉8785424592023-08-15 13:04:14
Vous pouvez refactoriser textTransformer()
方法,接受一个泛型参数,并使用条件类型来检查 toNumberIfNeeded
是否为 true
或 false
。我认为 TypeScript 无法自动缩小返回值的类型。你必须使用类型断言,否则返回类型将被推断为 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