简体   繁体   English

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

[英]TypeScript custom typecheck for string length

I'm writing a react component that needs a string prop with a length of less than 10 characters.我正在编写一个需要长度小于 10 个字符的字符串 prop 的 react 组件。

I want the compiler to throw an error if a user passes a string with a length greater than 10.如果用户传递长度大于 10 的字符串,我希望编译器抛出错误。

interface ComponentProps {
    word: StringLessThanTenChar
}

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

How do I create a custom type to check this and throw an error?如何创建自定义类型来检查这一点并抛出错误?

It's not possible to make a type which checks for string length.不可能创建一个检查字符串长度的type You should do this programmatically.您应该以编程方式执行此操作。

You could do it by a regex or by length.您可以通过正则表达式或长度来完成。 Something like this.像这样的东西。

const string = 'lalalalalalalallallalalala'

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

1.First, it's not supported by typescript at this moment 1.首先,目前打字稿不支持

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


2.You can use regex to limit the length of string 2.您可以使用正则表达式来限制字符串的长度

For example:例如:

/^.{0,10}$/i

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


3.You can use RegExp.prototype.test() to test if a value fit your regex in js 3.您可以使用RegExp.prototype.test()来测试一个值是否适合您在 js 中的正则表达式

xxxx.test(yourValue)
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;
}

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

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