Extending interfaces and types
An interface or type can also be extended, but again, the syntax will differ as shown in the following code block:
// Extending an interface
interface IWork {
company: string
position: string
}
interface IPerson extends IWork {
name: string
age: number
}
// Extending a type
type TWork = {
company: string
position: string
}
type TPerson = TWork & {
name: string
age: number
}
// Extending an interface into a type
interface IWork {
company: string
position: string
}
type TPerson = IWork & {
name: string
age: number
}
As you can see, by using the &
character, you can extend a type, while you extend an interface using the extends
keyword.
Understanding the extension of interfaces and types paves the way for us to delve into their implementation. Let us transition to illustrating how classes in TypeScript can implement these interfaces and types while keeping in mind the inherent constraints when dealing with union types.