typescript - 使用类方法更新属性时打字稿类型缩小过于严格
问题描述
在使用类方法更新属性时,Typescript 是否应该对类型缩小如此严格?我并不是说 Typescript 应该以某种方式分析一个方法在做什么,但是通过方法修改类实例属性是一种常规做法。
我知道currentChar
从普通属性或属性 getter 更改为方法可以解决这个问题,但我认为属性和 getter 非常有价值。
export class Parser {
data = "abcdefg"
currentIndex = 0
get currentChar(): string {
return this.data[this.currentIndex]
}
nextChar(): void {
++this.currentIndex
}
}
(() => {
const parser = new Parser()
if (parser.currentChar !== "a") {
return
}
const aChar: "a" = parser.currentChar // = type 'a', value 'a'
parser.nextChar()
const bChar: "a" = parser.currentChar // = type 'a', value 'b'
if (parser.currentChar === "b") { // Error: This condition will always return 'false' since the types '"a"' and '"b"' have no overlap.
console.log("current char really equals 'b'")
}
})();
解决方案
这是控制流分析的局限性。由于您检查了类属性,因此该属性的类型将被检查缩小,并且在调用方法时打字稿不会清除这种缩小。
您可以在此处阅读有关此内容的更多信息
推荐阅读
- python - 将 pandas groupy 的第二个列表项的级别带入一列
- javascript - JS如何使var长度限制
- python - 在 Pandas 数据框中查找段
- nginx - 如何在重写期间对字符串(request_uri)进行base64编码?
- javascript - 为什么我的js有错误?我的错误“未使用的默认导出”
- django - Django Select 2 Widget 不工作,已渲染字段但未应用样式
- python - 为什么我会为一种方法获得 AttributeError 而不是其他方法?
- python - (Python)有没有办法在一行中清除 Tkinter UI 中的所有输入框?
- webpack - ScriptExternalLoadError:加载脚本失败。vue-cli@5.0.0-rc.0
- deep-learning - 在 torch.nn.Sequential 中重新排列神经网络层