![](/img/trans.png)
[英]TS2322: Type '(data: TicketFullDTO) => Promise<void>' is not assignable to type 'FormEventHandler<HTMLFormElement>'
[英]angular2 TS2322 Type 'Promise<void>' is not assignable to type 'Promise<string>' when given a string
使用Angular 2,我有一個處理我的API調用的服務。 在服務中,我有一個handleError函數,該函數為錯誤消息返回Promise<string>
。 我正在嘗試向handleError添加一些功能,如果存在憑據錯誤,該功能將在以后將頁面重定向到登錄屏幕。 當我這樣做時,即使我返回相同的Promise,然后嘗試從中刪除鏈條,TypeScript也會引發TS2322錯誤。
錯誤TS2322:類型'Promise <void>'無法分配給類型'Promise <string>'。 類型“ void”不可分配給類型“ string”。
private handleError(error: Error): Promise<string> {
let message = "Something went wrong loading data from the API.";
if (error.response.status === 0) {
message = "Unable to contact server. Please file a bug report.";
}
if (error.message) {
message = "API Service Error retrieving page: " + error.message;
}
this.alerts.error(message);
if (error.response.status === 403) {
if (error.message.indexOf("Authentication credentials") !== -1) {
return Promise.reject<string>(message) // this line errs with TS2322
.then(() => this.appState.refresh())
.then(() => this.redirects.login())
.then(() => this.alerts.warning("Redirected to login because no credentials found."));
} else {
this.redirects.index();
}
}
return Promise.reject<string>(message);
}
return Promise.reject<string>(message) // this line errs with TS2322
.then(() => this.appState.refresh())
.then(() => this.redirects.login())
.then(() => this.alerts.warning("Redirected to login because no credentials found."));
Typescript對您大吼大叫,因為appState.refresh
, redirects.login
或alerts.warning
返回空值。 為了正確地鏈接它,請使用鏈接設置一個變量,然后返回該變量:
let result = Promise.reject<string>(message);
result.then(() => this.appState.refresh())
.then(() => this.redirects.login())
.then(() => this.alerts.warning("Redirected to login because no credentials found."));
return result;
值得一提的是,因為您的Promise被拒絕,所以不會調用then
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.