Implementing interfaces and types
A class can implement an interface or type alias in the exact same way. But it cannot implement (or extend) a type alias that names a union type
. For example:
// Implementing an interface
interface IWork {
company: string
position: string
}
class Person implements IWork {
name: 'Carlos'
age: 35
}
// Implementing a type
type TWork = {
company: string
position: string
}
class Person2 implements TWork {
name: 'Cristina'
age: 34
}
// You can't implement a union type
type TWork2 = { company: string; position: string } | { name: string; age: number }
class Person3 implements TWork2 {
company: 'Google'
position: 'Senior Software Engineer'
}
If you write the preceding code, you will get the following error in your editor:
Figure 2.3: A class can only implement an object type or intersection of object types with statically known members
As you can see, you are not able to implement a union type.