javascript - 访问数组属性时出现编译错误

标签 javascript node.js typescript

我已经声明了这种类型:

export type Maybe<T> = T | null;

export type HostelId = {
  id: Scalars['String']
}

我在此函数中使用

book (hostel: Array<Maybe<HostelId>>) : boolean {
    console.log (hostel.id[])
}

但是我收到这个编译错误

Property 'id' does not exist on type 'Maybe<HostelId>[]'.

最佳答案

您的代码遇到的唯一问题是您正在访问 id 属性 在 Array 对象上,而不是实际的 HostelId 对象上。

export type Maybe<T> = T | null;

export type HostelId = {
  id: String
}


function book (hostel: Array<Maybe<HostelId>>) : boolean {
    hostel.map((h) => {
      // I wrote this if statement in order to suppress the
      // "Object is possibly 'null'." error
      if (h != null && h.id != null){
        console.log(h.id)
      }
    })
}

let x : HostelId = {id: 'asdf'}
book([x])

关于javascript - 访问数组属性时出现编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59561204/

相关文章:

javascript - 如何从 mac 上网页中的链接启动应用程序

javascript - 具有改变 redux 状态的原型(prototype)的数组

javascript - 子页面与react-router 4不匹配

typescript - Next.js - 在构建时使用 getStaticProps 生成持久布局

javascript - 'this' 绑定(bind)到订阅函数而不是 Angular2 中的外部组件范围

javascript - 如何在javascript中验证数字和大写字母

javascript - Angular 复选框指令

node.js - NodeJS Bookshelf 用户-追随者关系示例

javascript - 在 for 循环中链接 Promise 的最佳方式是什么?

typescript :跨多个文件的同一命名空间内的可见性