typescript - 如何检查字符串是否仅包含空格或在 TypeScript 中为空?

标签 typescript

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

我试过这个功能:

export const isEmpty = function(text: string): string {
  return text === null || text.match(/^ *$/) !== null;
};

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

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

最佳答案

错误 Type 'boolean' is not assignable to type 'string' 是由于函数签名指示返回类型是 string ,当它实际返回时一个 bool 值

定义应该是:

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;
}

关于typescript - 如何检查字符串是否仅包含空格或在 TypeScript 中为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57476487/

相关文章:

TypeScript:错误:使用路径时找不到模块

reactjs - 在 TypeScript 项目之间共享代码(使用 React)?

typescript - dc.js 在 typescript 中输入

javascript - AngularJS 和 Typescript - 注入(inject)服务

javascript - TypeScript - 如何从事件处理程序方法访问类实例

typescript - 该表达式不可构造。类型 'typeof import("jspdf")' 没有构造签名

javascript - 定义 Typescript 接口(interface),其中属性是现有对象的属性

Angular2 拖放目标

typescript - 如何从现有的 JavaScript 库生成 .d.ts "typings"定义文件?

css - 使用定时器连续循环遍历数组