我正在尝试创建一个使用TypeScript处理空白或空字符串的函数
我试过这个功能:
export const isEmpty = function(text: string): string {
return text === null || text.match(/^ *$/) !== null;
};但我得到了Type 'boolean' is not assignable to type 'string'
使用TypeScript检查字符串是空的还是只包含空格和制表符的最佳方法是什么?
发布于 2019-08-13 11:38:48
错误Type 'boolean' is not assignable to type 'string'是由于函数签名导致的,它指示返回类型在实际返回boolean时是string。
定义应是:
export const isEmpty = function(text: string): boolean {
return text === null || text.match(/^ *$/) !== null;
};全白空间
请注意,空格可以是下列任何一种:
要处理这些情况,正则表达式应该是:
/^\s*$/该函数可以写成:
export function isEmpty(text: string): boolean {
return text == null || text.match(/^\s*$/) !== null;
}发布于 2019-08-13 11:20:42
不需要Regex。简单地做
export const isEmpty = function(text: string): boolean{
return (!text || text.trim() === "");
};发布于 2019-08-13 11:14:18
您正在返回boolean,但您的函数希望得到string,因此将其更改如下:
export const isEmpty = function(text: string): boolean {
return text === null || text.match(/^ *$/) !== null;
};您也不能设置预期的返回类型,并让TypeScript编译器从实现中推断它是boolean。
export const isEmpty = function(text: string) {
return text === null || text.match(/^ *$/) !== null;
};https://stackoverflow.com/questions/57476487
复制相似问题