TypeScript - Structural Typing & Variance
Structural typing
type HasId = { id: string };
function takeId(x: HasId) {}
const obj = { id: 'x', extra: 1 };
takeId(obj); // ok (duck typing)
Assignment compatibility
type A = { a: number };
type B = { a: number; b: number };
const b: B = { a:1, b:2 };
const a: A = b; // ok (B is a superset)
Variance (high level)
- Function parameters are checked bivariantly by default (for compatibility).
- Use generic constraints and careful design to avoid unsafe substitutions.