TS2769 No overload matches this call
Смотрю обучающий ролик на ютубе, как добавить token в ответное сообщение. Имеется сервис, где получаем token
get token (): string | null {
const fbTokenExp = localStorage.getItem('fb-token-exp');
if (fbTokenExp) {
const expDate = new Date(fbTokenExp);
if ( new Date > expDate ) {
this.logout()
return null
}
return localStorage.getItem('fb-token')
}
return null;
}
и сам intercept где происходит добавление token в сообщение
intercept(req: import("@angular/common/http").HttpRequest<any>,
next: import("@angular/common/http").HttpHandler): import("rxjs").Observable<import("@angular/common/http").HttpEvent<any>> {
if (this.auth.isAuthenticated()) {
req = req.clone({
setParams: {
auth: this.auth.token
}
})
}
IDEA ругается на эту строку
auth: this.auth.token
Пишет, что
TS2769: No overload matches this call. Overload 1 of 3, '(update: { headers?: HttpHeaders | undefined; context?: HttpContext | undefined; reportProgress?: boolean | undefined; params?: HttpParams | undefined; ... 6 more ...; setParams?: { ...; } | undefined; }): HttpRequest<...>', gave the following error. Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'. Overload 2 of 3, '(update: { headers?: HttpHeaders | undefined; context?: HttpContext | undefined; reportProgress?: boolean | undefined; params?: HttpParams | undefined; ... 6 more ...; setParams?: { ...; } | undefined; }): HttpRequest<...>', gave the following error. Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.
Я не пойму как это исправить.
Ответы (1 шт):
Автор решения: Alexy
→ Ссылка
SetParams имеет тип:
{
[param: string]: string;
}
Вы же скорей всего передаете значение которое может быть undefined либо сам this.auth либо его свойство this.auth.token
Проверяйте существует ли свойство
if (this.auth && this.auth.token) {
req = req.clone({
setParams: {
auth: this.auth.token
}
})
}
Либо используйте оператор ! если уверены что свойство есть
if (this.auth.isAuthenticated()) {
req = req.clone({
setParams: {
auth: this.auth!.token!
}
})
}