我正在尝试为我的函数定义输出类型,我想根据toNumberIfNeeded标志在string和number类型之间设置条件,假设如果toNumberIfNeeded为真,则此函数将返回一个数字类型,反之返回字符串类型。我该如何做?
interface Options {
uppercase?: boolean;
filterSpecialChars?: boolean;
toNumberIfNeeded?: boolean;
}
export const textTransformer = (text: string, options?: Options) => {
const { uppercase, filterSpecialChars, toNumberIfNeeded} = options || {};
// 我的处理逻辑代码
return toNumberIfNeeded ? parseInt(text) : text;
}
预期的示例:
textTransformer('hello'); // 返回字符串类型
textTransformer('123', { toNumberIfNeeded: true }); // 返回数字类型 Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你可以重构
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