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'
}]
}
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'
}]
}
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.
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?
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.