0

I'm writing a react component that needs a string prop with a length of less than 10 characters.

I want the compiler to throw an error if a user passes a string with a length greater than 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?

3
  • @keikai - if you make your comment as an answer, I will accept as answer. Commented Mar 26, 2020 at 16:39
  • You would need refinement types to be able to do this in compile time which typescript doesn't support so you can only check it in runtime Commented Mar 27, 2020 at 5:44
  • Check this: medium.com/@lemoine.benoit/… Commented Aug 15, 2020 at 11:42

3 Answers 3

1

1.First, it's not supported by typescript at this moment

Refer: Issue about Suggestion of Regex-validated string type


2.You can use regex to limit the length of string

For example:

/^.{0,10}$/i

Try it online: https://www.regextester.com/?fam=115411


3.You can use RegExp.prototype.test() to test if a value fit your regex in js

xxxx.test(yourValue)
Sign up to request clarification or add additional context in comments.

Comments

1

It's not possible to make a type which checks for string length. 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

Comments

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.