Struggling with type assertions when dealing with multiple promise return types? Check out this simplified code snippet:
interface SimpleResponseType {
key1: string
};
interface SimpleResponseType2 {
property1: string
property2: number
};
interface ServiceType {
fetchResponse: () => Promise<SimpleResponseType | SimpleResponseType2>
};
class Service implements ServiceType {
async fetchResponse() {
// fetching api data and returning json here
return { key1: 'json' };
};
};
const service = new Service();
await service.fetchResponse().then(resp => {
// Expecting typeof SimpleResponseType
console.log(resp.key1)
})
An error is thrown by TypeScript on the last key1
line:
Property 'key1' does not exist on type 'SimpleResponseType2'.ts(2339)
Attempting to assert the type results in more errors. For instance, trying this assertion:
await service.fetchResponse().then((resp as SimpleResponseType) => {
Leads to this error:
Argument of type 'SimpleResponseType' is not assignable to parameter of type '(value: SimpleResponseType | SimpleResponseType2) => SimpleResponseType | SimpleResponseType2 | PromiseLike<...>'.
Type 'SimpleResponseType' provides no match for the signature '(value: SimpleResponseType | SimpleResponseType2): SimpleResponseType | SimpleResponseType2
The only working assertion found is:
const respTyped = resp as SimpleResponseType
Using respTyped
instead of resp
.
Perhaps there's a more effective approach to tackle this issue?