首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何检查字符串是否仅包含空白或TypeScript中为空?

如何检查字符串是否仅包含空白或TypeScript中为空?
EN

Stack Overflow用户
提问于 2019-08-13 11:08:44
回答 3查看 5.2K关注 0票数 2

我正在尝试创建一个使用TypeScript处理空白或空字符串的函数

我试过这个功能:

代码语言:javascript
复制
export const isEmpty = function(text: string): string {
  return text === null || text.match(/^ *$/) !== null;
};

但我得到了Type 'boolean' is not assignable to type 'string'

使用TypeScript检查字符串是空的还是只包含空格和制表符的最佳方法是什么?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-08-13 11:38:48

错误Type 'boolean' is not assignable to type 'string'是由于函数签名导致的,它指示返回类型在实际返回boolean时是string

定义应是:

代码语言:javascript
复制
export const isEmpty = function(text: string): boolean {
  return text === null || text.match(/^ *$/) !== null;
};

全白空间

请注意,空格可以是下列任何一种:

  • 空间特征
  • 制表符字符
  • 回车字符
  • 新行字符
  • 垂直制表符字符
  • 形式馈送字符

要处理这些情况,正则表达式应该是:

代码语言:javascript
复制
/^\s*$/

该函数可以写成:

代码语言:javascript
复制
export function isEmpty(text: string): boolean {
  return text == null || text.match(/^\s*$/) !== null;
}
票数 6
EN

Stack Overflow用户

发布于 2019-08-13 11:20:42

不需要Regex。简单地做

代码语言:javascript
复制
export const isEmpty = function(text: string): boolean{
  return (!text || text.trim() === "");
};
票数 4
EN

Stack Overflow用户

发布于 2019-08-13 11:14:18

您正在返回boolean,但您的函数希望得到string,因此将其更改如下:

代码语言:javascript
复制
export const isEmpty = function(text: string): boolean {
  return text === null || text.match(/^ *$/) !== null;
};

您也不能设置预期的返回类型,并让TypeScript编译器从实现中推断它是boolean

代码语言:javascript
复制
export const isEmpty = function(text: string) {
  return text === null || text.match(/^ *$/) !== null;
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57476487

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档