TypeScript自定义类型检查字符串长度

时间:2020-03-26 11:58:38

标签: reactjs typescript

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

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

interface ComponentProps {
    word: StringLessThanTenChar
}

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

如何创建自定义类型以检查此类型并引发错误?

3 个答案:

答案 0 :(得分:1)

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

您可以按正则表达式或按长度进行操作。像这样的东西。

const string = 'lalalalalalalallallalalala'

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

答案 1 :(得分:1)

1。首先,打字稿目前不支持

引荐:有关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 :(得分:0)

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;
}
相关问题