Let's say I have an interface:
interface Person {
age: number
name: {
first: string
second: string
}
}
And I want to extend Person
to Friend
, which would look exactly the same as Person
but with an added nickname
value in name
, like so:
interface Friend {
age: number
name: {
first: string
second: string
nickname: string | null
}
}
I know I could do...
interface Friend extends Person {
nickname: string | null
}
...but this would add it outside of name
.
I can't figure out any way to achieve this, any ideas?
CodePudding user response:
You can extract name: { first: string, second: string }
into a separate interface and extend that.
Ex.:
interface Person {
age: number
name: Name
}
interface Friend extends Person{
name: FriendName
}
interface Name {
first: string
second: string
}
interface FriendName extends Name {
nickname?: string
}
CodePudding user response:
You can do this by using the type
keyword instead of interface
:
type Friend = Person & {
name: {
nickname: string
}
};