首页 > 解决方案 > 值被声明并且仅在打字稿中的 if 语句之外使用

问题描述

在打字稿中,我的代码如下:

let a = 'null'
if (condition) {
  const a = 'condition was met'
}
const result = getName(a)

const a = 'condition was met'但是,编译/构建失败,因为 a in say下方有一条黄线a is declared but its value is never read。有谁知道对此的修复,以便以后可以使用 a 并且我可以在 if 语句中更改它的值?如果我尝试删除,我会在“说let a = 'null'”下得到一个红色下划线const result = getName(a)Cannot find name 'a'

标签: typescriptscopeconstantsdeclaration

解决方案


因为变量 shadowing和if 块let a内部const a不一样。

你应该这样写:

let a = 'null'
if (condition) {
  a = 'condition was met'
}
const result = getName(a)

我也认为您应该阅读有关letconst的文档


推荐阅读