【问题标题】:How can I define the object type in a returned pipe(map(...)) statement?如何在返回的 pipe(map(...)) 语句中定义对象类型?
【发布时间】:2021-11-25 16:13:52
【问题描述】:

我开始在 Angular + Ionic 框架中开发应用程序。

我的问题是我不知道如何定义返回对象的类型以便能够检索特定属性。

我认为这是一个常见问题,但我无法使用 google 找到正确的结果。

当我尝试从设备存储中返回我的身份验证令牌时,它看起来像

{
   key:'authData',
   value: token
}

我无法编译,因为我的 value 属性在返回的 storedData 字段中未知。

错误 TS2339:“未知”类型上不存在属性“值”。

return from(Storage.get({ key: 'authData' })).pipe(map(storedData => {
  if (!storedData || !storedData.value) {
    return null;
  }
  const parsedData = JSON.parse(storedData.value)
}

所以我正在寻找某种类型来定义存储数据对象上的接口类型。 亲切的问候!

【问题讨论】:

标签: javascript angular typescript ionic-framework


【解决方案1】:

您必须在文件顶部声明模型

interface StoredData {
   key: string;
   value: string;
}

然后在您的代码中:

return from(Storage.get({ key: 'authData' })).pipe(map(storedData: StoredData => {
  if (!storedData || !storedData.value) {
    return null;
  }
  const parsedData = JSON.parse(storedData.value)
 }

您也可以通过以下方式欺骗 linter:

return from(Storage.get({ key: 'authData' })).pipe(map(storedData => {
  if (!storedData || !storedData['value']) {
    return null;
  }
  const parsedData = JSON.parse(storedData['value'])
 }

【讨论】:

    猜你喜欢
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多