简体   繁体   English

Typescript中的字符串验证

[英]String validation in Typescript

Coming from Javascript I need some advice on how to do string validation in Typescript. 来自Javascript,我需要一些有关如何在Typescript中进行字符串验证的建议。

Usually in Javascript you can just check the string as if it was a boolean, but with strong types, you get a compiler error. 通常,在Javascript中,您可以像检查布尔值一样检查字符串,但是如果使用强类型,则会出现编译器错误。

A couple of solutions I thought of, but don't really like is you could do !!myString or change the return type. 我想到了几个解决方案,但我不太喜欢的是您可以做!! myString或更改返回类型。 Is checking for null, undefined and empty string the way to do it? 是检查null,undefined和empty字符串的方法吗?

See example: 参见示例:

function stringIsValid(myString: String) : Boolean {
    return myString; // compiler error
}

var isValid = stringIsValid(null);

Playground 操场

You probably want to just use one of these, functionally they're the same: 您可能只想使用其中之一,在功能上它们是相同的:

function stringIsValid(myString: String): Boolean {
    return Boolean(myString);
}

or 要么

function stringIsValid(myString: String): Boolean {
    return !!myString;
}

The types from TS will not help you do runtime type validation on your variables, because TS only works at compile-time. TS中的类型将无法帮助您对变量进行运行时类型验证,因为TS仅在编译时起作用。 There is a handy typeof command in JS to do type validation: JS中有一个方便的typeof命令可以进行类型验证:

typeof myString === 'string'

The function you wrote 您编写的功能

function stringIsValid(myString: string) : boolean {
    return myString;
}

will give you TS error at transpilation (compile-time), but these types will have no effect when you actually run your program. 会在编译(编译时)时给您TS错误,但是当您实际运行程序时,这些类型将无效。 Here's an example of how to write it with proper typing and proper runtime check: 这是一个如何使用正确的键入和正确的运行时检查来编写它的示例:

function stringIsValid(myString: string) : boolean {
    return typeof myString === 'string';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM