如何解决Typescript / React TypeError:无法读取未定义的属性'MaxEmailLength'
我在打字稿方面遇到了一个奇怪的问题,所以我有两个静态类互相使用,这是行不通的。
Class ValidationHelper(单个文件)
import { ValidationErrors } from '../dictionary/ValidationErrors';
export class ValidationHelper {
static readonly MaxEmailLength = 320;
static IsEmailValid(email: string): ValidationResult {
if (email.length < 0) {
return new ValidationResult(false,ValidationErrors.MissingEmail);
}
if (email.length > this.MaxEmailLength) {
return new ValidationResult(false,ValidationErrors.InvalidEmailLength);
}
return new ValidationResult(true);
}
}
Class ValidationErrors(单个文件)
import { ValidationHelper } from "../helpers/ValidationHelper";
export class ValidationErrors {
static readonly MissingEmail = "Please provide email.";
static readonly InvalidEmailLength = `Email can't be longer than ${ValidationHelper.MaxEmailLength} characters.`;
}
这些类在react组件中使用。一切都由webpack 4.44.1构建到vendor.js runtime.js和每个需要的文件中。然后使用<script>
标签将这些js文件加载到HTML页面中。
以下是我已安装的依赖项:
"devDependencies": {
"@babel/core": "^7.11.1","@babel/plugin-proposal-class-properties": "^7.10.4","@babel/plugin-proposal-object-rest-spread": "^7.11.0","@babel/plugin-transform-runtime": "^7.11.0","@babel/preset-env": "^7.11.0","@babel/preset-react": "^7.10.4","@babel/preset-typescript": "^7.10.4","@typescript-eslint/eslint-plugin": "^3.9.0","@typescript-eslint/parser": "^3.9.0","babel-loader": "^8.1.0","css-loader": "^4.2.1","eslint": "^7.6.0","grunt": "^1.1.0","grunt-contrib-less": "^1.4.1","grunt-contrib-watch": "^1.1.0","jit-grunt": "^0.10.0","less-loader": "^6.2.0","style-loader": "^1.2.1","typescript": "^3.9.7","webpack": "^4.44.1","webpack-cli": "^3.3.12","webpack-dev-server": "^3.11.0","webpack-merge": "^5.1.1"
},"dependencies": {
"@babel/runtime": "^7.11.2","@types/react": "^16.9.46","@types/react-dom": "^16.9.8","grunt-contrib-concat": "^1.0.1","grunt-contrib-cssmin": "^3.0.0","grunt-contrib-jshint": "^2.1.0","grunt-terser": "^1.0.0","grunt-webpack": "^4.0.2","react": "^16.13.1","react-dom": "^16.13.1"
}
这是错误: TypeError:无法读取未定义的属性“ MaxEmailLength”
作为对此进行调查的一部分,我在代码中注释了很多,并将其留在了react组件的render方法中:
<p>{ValidationHelper.MaxEmailLength}</p>
,这不起作用。似乎一个简单的react组件将仅在render方法中的那一行失败。
我也已经在当前正在运行typescript / react的单独的不同项目/解决方案上尝试过此方法,但我遇到了相同的问题(看起来这是它的工作原理)。
作为另一项测试的一部分,我已将其移走
static readonly MaxEmailLength = 320;
将新的静态类分离出来即可使用。
这似乎是因为ValidationHelper类使用ValidationErrors类,然后ValidationErrors类使用ValidationHelper类。
此外,我可以添加为3.9.7打字稿版本。
我的问题是应该这样做吗?
解决方法
在TypeScript playground中,这确实对我有用。错误可能是您尝试使用的文件中没有ValidationHelper
吗?
仅供参考,我将其发布为答案,因为链接太长而无法放入评论中
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。