【发布时间】: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