CodePark/ questions / Abstract classes, interfaces & structural typing
START PRACTICINGPRACTICE
Backend question · Object-oriented programming › Abstract classes, interfaces & structural typing

What does TypeScript say about this check?

interface PaymentGateway {
  charge(amount: number): Promise<void>;
}

function isGateway(x: unknown): boolean {
  return x instanceof PaymentGateway;
}
Error: PaymentGateway only refers to a type, but is being used as a value

It is a compile error: "only refers to a type, but is being used as a value here". instanceof needs a real constructor at runtime. Interfaces are erased, so there is nothing to check against.

"It compiles and checks whether
x has a charge method" is the tempting idea, but TypeScript never writes shape checks for you. Use an abstract class if you need instanceof, or write a type guard: typeof (x as any)?.charge === "function".