What is structural compatibility and how does it affect assignability in TypeScript?

Answer

TypeScript's assignability rules (based on structural compatibility) determine when a value of type A can be used where type B is expected. A type S is assignable to type T if S has at least the same properties with compatible types as T — S can have more properties, but not fewer. For functions: a function is assignable to another if its parameters are compatible (contravariant — more general is OK) and its return type is compatible (covariant — more specific is OK). Key rules: Every type is assignable to itself. never is assignable to every type. Every type is assignable to unknown. Only never is assignable to never. Subclasses are assignable to base classes. Discriminated unions: members are assignable to the union, not vice versa. Optional properties: { name: string } is assignable to { name?: string } but not the reverse. Understanding assignability is foundational to TypeScript — all type errors are ultimately assignability violations. The TypeScript spec details the exact algorithm in terms of "Is type A assignable to type B?"