Typescript检查字符串是否为空作为布尔值

Typescript检查字符串是否为空作为布尔值,typescript,casting,type-conversion,conventions,Typescript,Casting,Type Conversion,Conventions,是否有“正确”的方法来检查typescript中的字符串是否为空,并以布尔值形式返回答案?在JavaScript中,我通常只使用空字符串为false的事实,但Typescript不喜欢在类型之间转换。Typescript可以使用很多方法,但我只是好奇有一种“标准”的方法 比如说, const emptyString: string = ''; const nonEmptyString: string = 'something'; function stringIsEmpty(str: stri

是否有“正确”的方法来检查typescript中的字符串是否为空,并以布尔值形式返回答案?在JavaScript中,我通常只使用空字符串为false的事实,但Typescript不喜欢在类型之间转换。Typescript可以使用很多方法,但我只是好奇有一种“标准”的方法

比如说,

const emptyString: string = '';
const nonEmptyString: string = 'something';

function stringIsEmpty(str: string): boolean {
    return str; // Type 'string' is not assignable to type 'boolean'.
}
为了解决这个问题,我们可以做以下任何一项(以及其他),但在我看来,他们都感觉有点“黑客行为”:

返回!!str

返回布尔值(str)

返回str.length>0


return/^$/.test(str)

您还可以将其强制转换为布尔值:

return str as unknown as boolean;

如果要将其视为布尔值,为什么不从
stringIsEmpty
返回str===''
?这将返回一个实际的布尔值,作为适当运行时检查的结果。@Jeffrey Westerkamp这是一个很好的观点,我不知道为什么我没有想到这一点!