Type compatibility helps TypeScript check if one class can be used where another is expected. It makes your code safer and easier to work with.
Type compatibility with classes in Typescript
class ClassA { propertyA: string; } class ClassB { propertyA: string; propertyB: number; } let a: ClassA; let b: ClassB; a = b; // Allowed if ClassB has at least the properties of ClassA // b = a; // Error if ClassA lacks properties of ClassB
TypeScript uses 'structural typing', meaning compatibility depends on the shape (properties) of the classes, not their names.
Extra properties in the source class are okay when assigning to a target with fewer properties.
class Animal { name: string; } class Dog { name: string; breed: string; } let animal: Animal; let dog: Dog = { name: "Buddy", breed: "Beagle" }; animal = dog; // OK: Dog has all Animal properties // dog = animal; // Error: Animal lacks 'breed'
class Point { x: number; y: number; } class NamedPoint { x: number; y: number; name: string; } let point: Point = { x: 1, y: 2 }; let namedPoint: NamedPoint = { x: 1, y: 2, name: "A" }; point = namedPoint; // OK // namedPoint = point; // Error
This shows that an Employee can be used where a Person is expected because it has all Person's properties.
class Person { name: string; constructor(name: string) { this.name = name; } } class Employee { name: string; employeeId: number; constructor(name: string, id: number) { this.name = name; this.employeeId = id; } } let person: Person; let employee = new Employee("Alice", 123); person = employee; // OK because Employee has 'name' console.log(person.name); // Prints 'Alice' // let newEmployee: Employee = person; // Error: Person lacks 'employeeId'
Type compatibility is based on properties, not class names.
Private or protected members affect compatibility differently; only public members are checked structurally.
Be careful when assigning classes with methods; method signatures must also be compatible.
TypeScript checks if classes have matching properties to decide compatibility.
You can assign an instance of a class with more properties to a variable typed as a class with fewer properties.
Compatibility helps write flexible and safe code by focusing on object shapes.