【问题标题】:Typescript Interface[] vs [Interface]打字稿接口 [] 与 [接口]
【发布时间】:2019-05-24 23:51:12
【问题描述】:

我正在尝试将 Article 数组分配给我的 mongoose 文档,但 Typescript 似乎不喜欢这样,我不知道为什么它会显示此警告/错误,即它不可分配。

我的猫鼬模式和接口(简化):

interface Profile {
  username: string,
  articles: [Article]
}

interface Article {
  index: number,
  name: string,
}

// Mongoose model
export interface IProfile extends Profile, Document { }
const Article = new Schema({
  index: { type: Number, required: true },
  name: { type: String, required: true },
}, { _id: false })

const Profile = new Schema({
  username: { type: String, index: true },
  upcomingChests: { type: [Article] },
}, { timestamps: true })

export const Profile = model<IProfileModel>('IProfile', Profile)

我的代码尝试分配文章:

const profile: Profile = values[0]
const articles: Array<Article> = values[1]
profile.articles = articles // Error/Warning pops up in this line

[ts] 类型“Article[]”不可分配给类型“[Article]”。
“Article[]”类型中缺少属性“0”。

我的问题:

为什么它说它不可分配,[Article] 和 Article[] 之间有什么区别?

【问题讨论】:

标签: node.js typescript mongoose


【解决方案1】:

[Article] 有不同的含义:tuple 类型,带有 1 个 Article 元素。

您可能想使用Article[],与Array&lt;Article&gt; 的类型相同。

【讨论】:

  • 所以我应该更改 Profile 的界面,使其显示 articles: Article[] 对吗?
  • 我不能对你的实际数据说太多,但这应该可以解决类型不匹配的问题(并且更有可能在这里使用)。
猜你喜欢
  • 2017-09-02
  • 2019-09-23
  • 2020-08-14
  • 2019-05-04
  • 1970-01-01
  • 2013-01-26
  • 2021-02-04
  • 2017-04-15
相关资源
最近更新 更多