我正在try 弄清楚如何将类型保护与非参数变量一起使用.实际的场景是一个类的属性,但我try 用块外的变量来简化它.
let x: string | undefined
function fn() {
setX()
x.toLowerCase() // x might be undefined
}
function setX() {
x = "foo"
}
更适用的示例:
class FooWidget {
private el: Element | undefined
public display() {
this.createElementIfNotExists()
this.el.classList.add("display") // this.el possibly undefined
}
private createElementIfNotExists() {
if (this.el) return
this.el = document.createElement("div")
document.body.appendChild(this.el)
}
}