TypeScript 检查空字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44688840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:44:36  来源:igfitidea点击:

TypeScript check for empty string

typescripttypescript2.0

提问by Alexander Mills

Is there a way for TypeScript to statically check for an empty string? Is there a way to statically require a non-empty string to be passed to a function?

TypeScript 有没有办法静态检查空字符串?有没有办法静态地要求将非空字符串传递给函数?

let fn = function(a:string){

};

fn('');

or

或者

let a = '';
fn(a);

Can TS help us here?

TS 能帮到我们吗?

采纳答案by Rob

I believe this is as close as you're going to get only using the typing system (rather than having a 'nonEmptyString' class)

我相信这与您仅使用打字系统(而不是使用“nonEmptyString”类)一样接近

type nonEmptyString = never; // Cannot be implicitly cast to
function isNonEmptyString(str: string): str is nonEmptyString {
    return str && str.length > 0; // Or any other logic, removing whitespace, etc.
}

Testing it:

测试它:

let fn = function(a: nonEmptyString) {

}

let someStr = '';
if (isNonEmptyString(someStr)) {
    fn(someStr); // Valid
} else {
    fn(someStr); // Compile error
}

Unfortunately, you end up with warts since nonEmptyStringis never. Which means you need to explicitly cast nonEmptyStringback to string.

不幸的是,您最终会长疣,因为nonEmptyStringnever。这意味着您需要显式转换nonEmptyStringstring.

let fn = function(a: nonEmptyString) {
    let len = a.length; // Invalid
    let len2 = (<string>a).length; // Valid
    let str = a + 'something else'; // Valid (str is now typed as string)
}

One possible resolution is:

一种可能的解决方法是:

type nonEmptyString = string & { __nonEmptyStr: never };

Which alleviates the problem of having to explicitly cast back to a string (all three tests above are valid), but does pollute the type with __nonEmptyStr(which will be undefinedif referenced).

这减轻了必须显式转换回字符串的问题(上述所有三个测试都是有效的),但确实会污染类型__nonEmptyStrundefined如果被引用将是)。

回答by Kiara Grouwstra

You could maybe type it with overloads such as to give a bad return type on ""that will make things error as soon as you use it elsewhere:

您可以使用重载键入它,例如给出错误的返回类型"",一旦您在其他地方使用它就会出错:

type MyFnType = {
  (a: "") => never;
  (a: string) => whatever;
}

function fn: MyFnType = ...

回答by Don Pérignon

The snipet below controls if the string is empty and even if there is empty space string

下面的 snipet 控制字符串是否为空,即使有空字符串

private checkRequired(text:string){
        if(text == null) return false;
        let n = text.length; 
        for (let i = 1; i < n; i++){
            if (text[i] !== " "){
                return true;
            }
        }  
        return false;
      }

if(this.checkRequired("bla bla blast")){
 ... do your stuff 
}