javascript - 分配之前使用的打字稿变量
问题描述
我在我的 Typescript / ReactJS 项目中看到一个错误,说Variable 'myVar' is used before being assigned. TS2454
我正在运行 TS 版本 4.2.3,这个错误出现在我的 IDE 中以及当我尝试运行代码时。但是,它在 jsFiddle ( https://jsfiddle.net/d79L4ju8/ ) 中运行良好,我不明白为什么会抛出错误,因为似乎声明并检查了变量:
interface testType {
id: string,
message: string,
}
let requestType = 'eventCreated';
let testVar = true;
let myVar: testType;
if (testVar) {
myVar = {
id: 'abc123',
message: 'message goes here',
}
}
switch (requestType) {
case 'eventCreated':
if (myVar !== undefined) { // error thrown here
console.log(myVar);
}
break;
case 'eventChanged':
if (myVar !== undefined) {
console.log(myVar);
}
break;
}
是什么导致这个失败?
解决方案
如果不分配 testVar,则 myVar 将在未初始化的情况下使用。您可以像这样重写代码:
interface testType {
id: string,
message: string,
}
let requestType = 'eventCreated';
let testVar = true;
let myVar: testType | undefined = undefined;
if (testVar) {
myVar = {
id: 'abc123',
message: 'message goes here',
}
}
switch (requestType) {
case 'eventCreated':
if (myVar !== undefined) { // error thrown here
console.log(myVar);
}
break;
case 'eventChanged':
if (myVar !== undefined) {
console.log(myVar);
}
break;
}
推荐阅读
- node.js - 添加计算字段猫鼬的最有效方法
- kotlin - 如何从 IntRange 初始化 Kotlin IntArray?
- jquery - 如何在 jQuery 中检查未定义的值 - 无法读取属性错误
- algorithm - 使用 Kruskal 算法找到图的最小生成树
- amazon-web-services - AWS 根账户无法访问组织账户
- expo - Expo 中的 OCR 功能
- javascript - Express 服务器路由问题
- python - 在网络刮板脚本的 for 循环中仅反转没有数字的字符串
- php - 带有ajax的php-mysql登录系统
- amazon-web-services - 如何将新容器附加到 AWS ECS 中正在运行的任务?