'How to add a value within specific key when extending an interface?

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?



Solution 1:[1]

You can do this by using the type keyword instead of interface:

type Friend = Person & {
   name: {
     nickname: string
   }
};

Solution 2:[2]

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
}

TS playground

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Deutsch
Solution 2 aaronlukacs