BeCuriouzBeCuriouz

Learn something new every day

🔷 TypeScript
🪝

Typing this and Callable Types

💡 A this parameter type-checks how a function is called, while call and construct signatures let object types describe functions and constructors.

In JavaScript, this inside a function depends on how the function is called — a common source of bugs. TypeScript lets you pin it down with a special this parameter: a fake first parameter named this that describes the object the method expects. It vanishes at runtime (it's type-only), but the compiler now checks that you call the function on the right kind of object.

ts
function reset(this: { count: number }) {
  this.count = 0;
}
const counter = { count: 5, reset };
counter.reset();      // ✅ this is { count: number }
const loose = reset;
loose();              // ❌ 'this' is undefined here

Functions are also just objects, so a type can describe one directly. A call signature uses (args): ReturnType inside an object type, letting you attach extra properties to a function. A construct signature adds the new keyword, describing something callable with new — a class or constructor.

ts
type Greet = {
  (name: string): string;   // call signature
  lang: string;             // extra property
};
type Ctor = {
  new (name: string): Animal; // construct signature
};

Use a call signature when a function also carries data (like greet.lang = 'en'), and a construct signature when you want to accept a class itself as an argument and new it inside — something the shorthand (name: string) => string arrow syntax can't express.

🪝 Typing this and Callable Types — BeCuriouz