【发布时间】:2021-06-16 16:14:35
【问题描述】:
我正在尝试创建一个函数,该函数将字符串转换为布尔值,并带有可选的回退,以防该函数不成功。我尝试了两种简单的方法,但我无法理解为什么它不起作用。
方法一: 使用条件类型。
type toBooleanReturnType<T> =
T extends undefined
? boolean | undefined
: boolean | T
/**
* Converts a string to a boolean
* @param str
* @param fallback the fallback value in case the string param is not 'true' nor 'false
* @returns
*/
export const toBoolean = <T = undefined>(
str: string,
fallback?: T,
): toBooleanReturnType<T> => {
if (str.trim() === 'true') return true;
if (str.trim() === 'false') return false;
if (fallback) return fallback;
return undefined;
};
我得到Type 'T' is not assignable to type 'toBooleanReturnType<T>' 的fallback 回报和
Type 'undefined' is not assignable to type 'toBooleanReturnType<T>' 为 undefined 返回。
方法二: 函数重载。
/**
* Converts a string to a boolean
* @param str
* @param fallback the fallback value in case the string param is not 'true' nor 'false
* @returns
*/
export function toBoolean<T>(
str: string,
fallback?: undefined,
): boolean | undefined
export function toBoolean<T>(
str: string,
fallback: T,
): boolean | T {
if (str.trim() === 'true') return true;
if (str.trim() === 'false') return false;
if (fallback) return fallback as T;
return undefined;
};
但我也收到undefined 返回的错误。 Type 'undefined' is not assignable to type 'boolean | T'.
这样做的正确方法是什么?
【问题讨论】:
标签: typescript overloading conditional-types