type Answer = { error: false; status: boolean } | { error: true; description: string };
async has_READ_EXTERNAL_STORAGEv1(): Promise<Answer> {
return await this.androidPermissions
.checkPermission(this.permission.READ_EXTERNAL_STORAGE)
//.then((current) => ({ error: false, status: current.hasPermission})) <--ERROR
//.then((current) => ({ error: false as const, status: current.hasPermission})) <--NO ERROR
.catch((error) => ({ error: true, description: error.message as string}));
}
ERROR
Type '{ error: boolean; status: boolean; } | { error: true; description: string; }'
is not assignable to type 'Answer'.
Type '{ error: boolean; status: boolean; }' is not assignable to type 'Answer'.
Type '{ error: boolean; status: boolean; }' is not assignable to type '{ error: false; status: boolean; }'.
Types of property 'error' are incompatible.
Type 'boolean' is not assignable to type 'false'.ts(2322)
p.s.: if I return it as 'as const' I don't get any error, however, when I use the function it does not detect the status property.
2nd ERROR
Property 'status' does not exist on type 'Answer'.
Property 'status' does not exist on type '{ error: true; description: string; }'
First Edit
async has_READ_EXTERNAL_STORAGEv1(): Promise<Answer> {
return await this.androidPermissions
.checkPermission(this.permission.READ_EXTERNAL_STORAGE)
.then((current) => ({ error: false, status: current.hasPermission} as Answer))
.catch((error) => ({ error: true, description: error.message as string} as Answer));
}
p.s.: when I use the function, it keeps telling me that the status property does not exist.
2nd Edit
await this.has_READ_EXTERNAL_STORAGEv1().then(answer => {
if (!answer.error) {
console.log(answer.status); // <--Error
// when I use the function, it keeps telling me that the status property does not exist.
} else {
console.log(answer.description);
}
});
CodePudding user response:
!answer.error
seems to be too vague for the compiler to infer the type.
answer.error === false
works as you expect.
await this.has_READ_EXTERNAL_STORAGEv1().then(answer => {
if (answer.error === false) {
console.log(answer.status);
} else {
console.log(answer.description);
}
});
Stackblitz: https://stackblitz.com/edit/typescript-yatio3?file=index.ts