简体   繁体   English

在不修改源的情况下扩展对象的 typescript 数组

[英]extend typescript array of object without modifying the source

I have this List object, but later on the shape changed, I need an extra id property, but how to not modify List?我有这个 List 对象,但是后来形状改变了,我需要一个额外的 id 属性,但是如何不修改 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'
    }]
}

You can extend the List interface您可以扩展List接口

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 use extends keyword for extend existing interface您可以使用extends关键字来扩展现有接口

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.或者您可以在现有的List界面中将 id 设为可选,因此如果您已经在不影响任何人的地方使用了它。

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

Note : ?注意? is used to make property optional.用于使属性可选。

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?
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM