繁体   English   中英

如何使用TypeScript的功能检查字符串中的字母是否大写?

[英]How can I check if a letter in a string is uppercase using the power of TypeScript?

我的问题很简短。 我是TypeScript的新手,一直到处搜索,但没有找到答案。

我有用C#编写的代码

private bool MaskValidateChar(KeyPressEventArgs e, int index)
{
    string c = e.KeyChar.ToString();
    if (Char.IsUpper(c[0])) //Need to this with TypeScript :-\
    {
        //Do Something....
    }
}

当我将上述代码转换为Type脚本时,我可以简单地编写类似if (c[0] == c[0].toUpperCase())

我只需要知道Typescript中是否有内置方法来检查给定字符是否为大写。 我在互联网上找不到这样的东西,但我对此表示怀疑。

请指教。

不能char.IsUpper/char.IsLower (TypeScript编译为JavaScript)没有类似于char.IsUpper/char.IsLower的内置方法。 您将必须进行比较,例如:

c[0] === c[0].toUpperCase() // c[0] is uppercase
c[0] === c[0].toLowerCase() // c[0] is lowercase

是的,您可以尝试使用linq

if (yourString.Any(char.IsUpper) &&
    yourString.Any(char.IsLower))

扩展@Saravana的答案,TypeScript的类型检查在运行时不存在,而是在编辑/转换时进行的检查。 这意味着不能仅根据变量的类型或内容自动引发异常。 缺少功能会导致错误,但是仅当您使用要针对的变量类型专用的功能时(该功能不专门用于大写/小写字符串),该功能才起作用。

选项? 好吧,如果您知道要处理一组特定的可能字符串,则可以设置一个type

type UCDBOperation = "INSERT" | "DELETE";
type LCDBOperation = "insert" | "delete";

function DoDBOperation(operation: UCDBOperation): void { ... }

const someUCOperation: UCDBOperation = ...;
const someLCOperation: LCDBOperation = ...;

DoDBOperation("INSERT");        // no error!
DoDBOperation(someUCOperation); // no error!
DoDBOperation("insert");        // type error
DoDBOperation(someLCOperation); // type error
DoDBOperation("fakeoperation"); // type error
DoDBOperation("FAKEOPERATION"); // type error

如果您只关心单个字母字符,则可以更进一步:

type UCAlpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z";

function printUpperCaseLetter(letter: UCAlpha): void {
  console.log(letter);
}

printUpperCaseLetter("A");     // no error!
printUpperCaseLetter("a");     // type error
printUpperCaseLetter("hello"); // type error
printUpperCaseLetter("WORLD"); // type error

请注意用户生成的字符串 在运行时生成的任何数据都不会对此类型进行检查:

// Typescript has no idea what the content
// of #SomeTextField is since that data
// wasn't available at transpile-time
DoDBOperation(document.querySelector("#SomeTextField").textContent);

暂无
暂无

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

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