Assignment compatibility means you can put one value into another variable without errors. It helps keep your program safe and working right.
How assignment compatibility is checked in Typescript
let targetVariable: TargetType;
targetVariable = sourceValue;The sourceValue must be compatible with the TargetType for the assignment to work.
TypeScript checks the structure and types to decide if the assignment is allowed.
let num: number; num = 5; // OK num = 'hello'; // Error
interface Person { name: string; age: number; }
let p: Person;
p = { name: 'Alice', age: 30 }; // OK
p = { name: 'Bob' }; // Errorlet x: { a: number }; let y = { a: 1, b: 2 }; x = y; // OK
This program shows that a Dog can be assigned to an Animal variable because Dog has all properties Animal needs.
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
let myPet: Animal;
let dog: Dog = { name: 'Buddy', breed: 'Beagle' };
myPet = dog; // OK because Dog has all Animal properties
console.log(myPet.name);TypeScript uses "structural typing" which means it checks if the shape of the data fits, not just the name.
Extra properties in the source are usually allowed when assigned to a target with fewer properties.
Assignment compatibility helps catch mistakes early before running the program.
Assignment compatibility means one value can be stored in a variable of another type if their shapes match.
TypeScript checks properties and types to decide if assignment is allowed.
This helps keep your code safe and avoid errors.