[英]TypeScript custom typecheck for string length
我正在編寫一個需要長度小於 10 個字符的字符串 prop 的 react 組件。
如果用戶傳遞長度大於 10 的字符串,我希望編譯器拋出錯誤。
interface ComponentProps {
word: StringLessThanTenChar
}
const Component: React.FC<ComponentProps> = props => {
return <div>{props.word}</div>;
};
<Component word="thisIsAStringLongerThan10Chars" />
如何創建自定義類型來檢查這一點並拋出錯誤?
不可能創建一個檢查字符串長度的type
。 您應該以編程方式執行此操作。
您可以通過正則表達式或長度來完成。 像這樣的東西。
const string = 'lalalalalalalallallalalala'
const stringLength = strin.split('').length
1.首先,目前打字稿不支持
參考:關於Regex-validated string type Suggestion 的問題
2.您可以使用正則表達式來限制字符串的長度
例如:
/^.{0,10}$/i
在線試用: https : //www.regextester.com/?fam=115411
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.