Strict Function Types: Method Versus Property Signatures

strictFunctionTypes checks property-signature callbacks contravariantly while method shorthand stays bivariant, so narrow params slip through methods.

TypescriptData Integrity

Code

typescriptsnippet
35 lines
interface Shape {
  name: string;
}

interface Circle extends Shape {
  radius: number;
}

const renderCircle = (shape: Circle): string => `circle r=${shape.radius}`;

// Property signature: strictFunctionTypes checks parameters contravariantly,
// so a paint that only knows Circle cannot sit behind a Shape contract.
interface Painter {
  paint: (shape: Shape) => string;
}

const anyShapePainter: Painter = { paint: (shape: Shape) => `shape ${shape.name}` };
// @ts-expect-error — renderCircle only accepts Circle, too narrow for Painter
const narrowPainter: Painter = { paint: renderCircle };

// Method shorthand: bivariant parameter checking, so the narrow param slips through.
interface MethodPainter {
  paint(shape: Shape): string;
}

const methodPainter: MethodPainter = {
  paint(shape: Circle): string {
    return renderCircle(shape);
  },
};

const unit: Circle = { name: 'unit', radius: 2 };
console.log(anyShapePainter.paint(unit));
console.log(narrowPainter.paint(unit));
console.log(methodPainter.paint(unit));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

shape unit
circle r=2
circle r=2

How this file behaves — Strict Function Types: Method Versus Property Signatures

Structurally, expect the function renderCircle and nothing else.

What to watch for

  • The import surface (if any) is all standard library, all versioned with the language itself.

Applying it

Entry signature: const renderCircle = (shape: Circle)

Statements that matter

const anyShapePainter: Painter = { paint: (shape: Shape) => `shape ${shape.name}` };
const renderCircle = (shape: Circle): string => `circle r=${shape.radius}`;
paint: (shape: Shape) => string;

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. The file defines `renderCircle` at load time.