Ionic 它对我说:型别'boolean'无法指派给型别'false',ts(2322),但是,我会传回正确的型别

wkyowqbh  于 2022-12-08  发布在  Ionic
关注(0)|答案(1)|浏览(172)
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);
  }
});
fnatzsnv

fnatzsnv1#

!answer.error似乎太模糊,编译器无法推断类型。
answer.error === false按您预期的方式工作。

await this.has_READ_EXTERNAL_STORAGEv1().then(answer => {
  if (answer.error === false) {
    console.log(answer.status);
  } else {
    console.log(answer.description);
  }
});

堆栈 lightning 战:https://stackblitz.com/edit/typescript-yatio3?file=index.ts

相关问题