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'
}]
}
CodePudding user response:
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'
}]
}
CodePudding user response:
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.
CodePudding user response:
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?
}