【问题标题】:TypeScript custom typecheck for string length用于字符串长度的 TypeScript 自定义类型检查
【发布时间】:2020-03-27 13:15:31
【问题描述】:

我正在编写一个需要长度小于 10 个字符的字符串道具的反应组件。

如果用户传递长度大于 10 的字符串,我希望编译器抛出错误。

interface ComponentProps {
    word: StringLessThanTenChar
}

const Component: React.FC<ComponentProps> = props => {
  return <div>{props.word}</div>;
};
<Component word="thisIsAStringLongerThan10Chars" />

如何创建自定义类型来检查并抛出错误?

【问题讨论】:

  • @keikai - 如果您将您的评论作为答案,我将接受。
  • 您需要细化类型才能在编译时执行此操作,而 typescript 不支持,因此您只能在运行时检查它

标签: reactjs typescript


【解决方案1】:

1.首先,目前typescript不支持

参考:关于Suggestion of Regex-validated string type的问题


2.可以使用regex来限制字符串的长度

例如:

/^.{0,10}$/i

在线试用:https://www.regextester.com/?fam=115411


3.您可以使用RegExp.prototype.test() 来测试一个值是否适合您在 js 中的正则表达式

xxxx.test(yourValue)

【讨论】:

    【解决方案2】:

    不可能创建一个检查字符串长度的type。您应该以编程方式执行此操作。

    您可以通过正则表达式或长度来完成。像这样。

    const string = 'lalalalalalalallallalalala'
    
    const stringLength = strin.split('').length
    

    【讨论】:

      【解决方案3】:
      import PropTypes from 'prop-types';
      
      interface ComponentProps {
          word: StringLessThanTenChar
      }
      
      const Mycomponent = props => {
          return <>{props.word}</>
      }
      
      Mycomponent.propTypes = {
        word: chkLength
      }
      
      function chkLength(props:ComponentProps , propName:any, componentName = 'ANONYMOUS') {
        if (props[propName]) {
          let value = props[propName];
          if (typeof value === 'string') {
              if(value.length > 10) {
                  new Error(propName + ' in ' + componentName + " is accept maximum 10 length of strings");
              }
          }
        }
        return null;
      }
      

      【讨论】:

        猜你喜欢
        • 2018-05-12
        • 2015-06-23
        • 1970-01-01
        • 2011-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多