【问题标题】:How can I check if a letter in a string is uppercase using the power of TypeScript?如何使用 TypeScript 的强大功能检查字符串中的字母是否为大写?
【发布时间】:2017-04-03 07:22:40
【问题描述】:

我的问题很简短。我是 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 中是否有内置方法来检查给定字符是否为大写。我在互联网上找不到这样的东西,但我对此表示怀疑。

请指教。

【问题讨论】:

    标签: c# typescript character uppercase


    【解决方案1】:

    是的。你可以试试 linq

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

    【讨论】:

    • 感谢您的回复。由于 TypeScript 的基本类型不包括 Chars,我认为我不能按原样使用它。这是真的吗?
    【解决方案2】:

    没有。 JavaScript(TypeScript 编译成的)没有类似于char.IsUpper/char.IsLower 的内置方法。你必须像这样比较它:

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

    【讨论】:

      【解决方案3】:

      扩展@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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-10
        • 1970-01-01
        • 2017-12-24
        • 2016-05-14
        • 2018-02-03
        • 1970-01-01
        相关资源
        最近更新 更多