Simple and common Angular2+ data service that handles errors and uses Promises:
// imports skipped
class DataType {}
class Error {
constructor(error: HttpResponse) {
this.error = error.json()
}
}
@Injectable()
export class MyService<DataType> {
apiUrl = 'my/url';
constructor(protected http) {}
get(): Promise<DataType[] | Error> {
return this.http
.get(this.apiUrl)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
protected handleError(error: HttpResponse): Promise<Error> {
console.error('An error occurred', error);
return Promise.reject(new Error(error));
}
}
In this class, get
method returns a Promise, which resolves with DataType[]
array, and rejects with Error
type.
Compiling this code, I'm getting this error:
Type 'Error | DataType[]' is not assignable to type 'DataType'. Type 'Error' is not assignable to type 'DataType'.
I'm using TypeScript version 2.4.2. I'm sure this started happening after TypeScript upgrade, which made types checks more strict.
I want to know how to handle rejection with different type in newest TypeScript. Are there different practices for doing this?
Update: I've found a corresponding bug report, not solved yet https://github.com/Microsoft/TypeScript/issues/7588
UPDATE
I've created a repo demonstrating the problem, with two commits. First commit uses <TypeResolve | TypeReject>
approach, second uses <TypeResolved>
only. Both commits seem to not compile in real life.
resolve
type. Thereject
type is alwaysany
. – Yodlereject
type to be the same asresolve
type – Tungusany
, regardless of the resolve type. When you sayPromise<string>
then only the resolve type isstring
, the reject type can be anything (any
) – YodlePromise<DataType[] | Error>
you just wantPromise<DataType[]>
– Calculator