Sub topic 2
Excess Property Checks and Compatibility
Assume basic TypeScript syntax, interfaces, type aliases, and JavaScript functions. The key idea is that TypeScript usually compares structure, but it adds a few context-sensitive checks.
Excess property checks on object literals
When an object literal is passed directly to a function or assigned to a typed variable, TypeScript checks for unknown properties. This is called an excess property check.
interface Point {
x: number;
y: number;
}
function logPoint(point: Point): void {
console.log(point.x, point.y);
}
// @ts-expect-error: "z" is not declared in Point
logPoint({ x: 1, y: 2, z: 3 });
const pointWithExtra = { x: 1, y: 2, z: 3 };
logPoint(pointWithExtra); // OKThe variable is accepted because its value has at least the required x and y members. Extra properties are allowed during normal structural assignment. The special check mainly catches spelling mistakes in fresh object literals.
Optional and readonly properties
An optional property may be absent. A readonly property may be read but cannot be changed through that type.
interface Settings {
color?: string;
readonly width: number;
}
const settings: Settings = { width: 10 };
settings.color = "blue";
// @ts-expect-error: width is readonly
settings.width = 20;readonly affects writing, not the property’s identity. It does not make nested objects immutable, and it does not create nominal typing.
Interfaces and type aliases
Interfaces and type aliases describe types in different syntaxes, but the checker compares their members structurally.
interface User {
id: number;
}
type Account = {
id: number;
};
const account: Account = { id: 1 };
const user: User = account; // OKThe names User and Account do not prevent assignment because both shapes contain the same required member.
Comparing function types
For functions, TypeScript compares parameter and return types. A function may ignore arguments supplied by its caller, so fewer parameters are usually acceptable. Return values must be compatible.
With strictFunctionTypes, parameter types are checked safely: a function accepting a broad type can replace one accepting a narrower type, but not the reverse.
type Handler = (event: string) => void;
const ignoresEvent: Handler = () => {};
const handlesEvent: Handler = event => console.log(event);Exercise
Why does logPoint({ x: 1, y: 2, z: 3 }) fail while passing the same object through a variable succeeds?
Show answer
The direct object is a fresh literal, so excess property checks reject z. The variable is checked structurally and contains the required x and y members.