错误 TS2339:类型 '{}' 上不存在属性'includes'



我遇到以下错误:

错误 TS2339:类型"{}"上不存在属性"包含"。

尝试检查用户名是否被占用时。 (当我评论此错误时,它完全有效,然后从ng serve开始,然后取消注释它,但我无法启动我的服务错误,这就是我使用这个技巧的原因(

服务:

isUsernameAvailable(){
const users = [];
return new Promise(function(resolve, reject){
firebase.database().ref('users').orderByKey().once('value').then(snapshot => {
snapshot.forEach(childSnapshot => {
if(childSnapshot.val().username){
users.push(childSnapshot.val().username);
}
})
resolve(users);
})
});

}

元件:

async checkUsername(){
const username=this.signupForm.get('username').value;
const usernames =await this.authService.isUsernameAvailable();
if(usernames.includes(username)){
this.usernameAvailable=false;
}
else {
this.usernameAvailable=true;
}
}

我看到有些人在 String[] 类型上遇到了类似的错误,并且问题出在 es2017 的 tsconfig 中,但我已经有了:

"lib": [
"es2017",
"dom"
]

我错在哪里?

首先,在这种情况下,不需要使用new Promise,您只需返回承诺即可。其次,您需要正确键入users作为string[]这将有助于返回类型推断。

isUsernameAvailable() {
return firebase.database().ref('users').orderByKey().once('value').then(snapshot => {
const users:string[]  = [];
snapshot.forEach(childSnapshot => {
if (childSnapshot.val().username) {
users.push(childSnapshot.val().username);
}
})
return users;
})
}

最新更新