Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

typescript的class,如何断言一个属性肯定存在?

如下,已经统一写了个函数判断属性是否存在,不存在会抛出错误,但是ts不认,请问有什么方法可以解决这个问题?

class {
 prop1?: sring
 clear() {
     this._check()
     this.prop1.split('') // 这里会提示this.prop1可能不存在
 }
 _check() {
     if (!this.prop1) {
        throw new Error('请先传入正确的参数')
     }
 }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

非空断言 this.prop1!.split('')
应该没错


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...