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}));
}
错误
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.:如果我以'as const'的形式返回它,我不会得到任何错误,但是,当我使用函数时,它不会检测status属性。
第二个错误
Property 'status' does not exist on type 'Answer'.
Property 'status' does not exist on type '{ 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} as Answer))
.catch((error) => ({ error: true, description: error.message as string} as Answer));
}
p. s.:当我使用该函数时,它一直告诉我status属性不存在。
第二次编辑
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);
}
});
1条答案
按热度按时间fnatzsnv1#
!answer.error
似乎太模糊,编译器无法推断类型。answer.error === false
按您预期的方式工作。堆栈 lightning 战:https://stackblitz.com/edit/typescript-yatio3?file=index.ts