扩展对象的打字稿数组,而无需修改源

发布于 2025-02-09 10:16:13 字数 375 浏览 1 评论 0原文

我有此列表对象,但是后来更改了形状,我需要一个额外的ID属性,但是如何不修改列表?

interface List {
    name: string //without adding id here
}

interface ListData {
    type: string
    lists: List[] //how to include id here?
}

const data: ListData = {
    type: 'something',
    lists: [{
        id: '1',
        name: 'alice'
    }, {
        id: '2',
        name: 'ja'
    }]
}

I have this List object, but later on the shape changed, I need an extra id property, but how to not modify List?

interface List {
    name: string //without adding id here
}

interface ListData {
    type: string
    lists: List[] //how to include id here?
}

const data: ListData = {
    type: 'something',
    lists: [{
        id: '1',
        name: 'alice'
    }, {
        id: '2',
        name: 'ja'
    }]
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

痴情 2025-02-16 10:16:13

您可以 Extend

interface List {
  name: string //without adding id here
}

interface ListId extends List {
  id: string
}

interface ListData {
  type: string
  lists: ListId[]
}

const data: ListData = {
  type: 'something',
  lists: [{
    id: '1',
    name: 'alice'
  }, {
    id: '2',
    name: 'ja'
  }]
}

You can extend the List interface

interface List {
  name: string //without adding id here
}

interface ListId extends List {
  id: string
}

interface ListData {
  type: string
  lists: ListId[]
}

const data: ListData = {
  type: 'something',
  lists: [{
    id: '1',
    name: 'alice'
  }, {
    id: '2',
    name: 'ja'
  }]
}
半山落雨半山空 2025-02-16 10:16:13

您可以使用扩展为扩展现有接口的关键字

interface ListWithId extends List {
  id: string;
}

,也可以在现有list> list>接口中创建ID可选,因此,如果您已经使用了它,则可以在没有影响任何一个的情况下使用它。

interface List {
  name: string;
  id?: string;
}

Note 用于使属性可选。

you can use extends keyword for extend existing interface

interface ListWithId extends List {
  id: string;
}

or you can make id optional in existing List interface so if you already used it some where it was not affect any one.

interface List {
  name: string;
  id?: string;
}

Note: ? is used to make property optional.

薄凉少年不暖心 2025-02-16 10:16:13

为以前的答案添加替代方法

type ListWithId = List & {id: string};

interface ListData {
    type: string
    lists: ListWithId[] //how to include id here?
}

,或者不漂亮,而是有效

interface ListData {
    type: string
    lists: (List & {id: string})[] //how to include id here?
}

to add alternative approach to previous answers

type ListWithId = List & {id: string};

interface ListData {
    type: string
    lists: ListWithId[] //how to include id here?
}

or, not pretty but works

interface ListData {
    type: string
    lists: (List & {id: string})[] //how to include id here?
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文