ThisType
Concept and syntax
ThisType<T> is a marker for contextual this typing in object literals when noImplicitThis is enabled. It does not add properties or bind a receiver. The implementation must supply a compatible receiver when the method is called.
Working example
Save each snippet separately as main.ts in a fresh directory with TypeScript 5.8.3. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts and run accepted snippets with node main.js. Type aliases are erased; assignments and diagnostic checks demonstrate the type relations, not the printed output alone.
type Model={count:number;inc():number} & ThisType<{count:number}>;const m:Model={count:2,inc(){return ++this.count;}}; console.log(m.inc());Expected output:
3Common mistake
Intentionally invalid; compile separately and do not execute.
type Model={count:number;inc():number} & ThisType<{count:number}>;const m:Model={count:2,inc(){return this.missing;}};Expected diagnostic: TS2339. The contextual receiver has count but no missing member.
Practice and recap
Add a decrement method with a matching receiver shape.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
ThisType — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about ThisType is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Model={count:number;inc():number} & ThisType<{count:number}>;const m:Model={count:2,inc(){return ++this.count;}}; console.log(m.inc());Which diagnostic and explanation match the rejected example under the lesson settings?
type Model={count:number;inc():number} & ThisType<{count:number}>;const m:Model={count:2,inc(){return this.missing;}};Which compiler option enables the intended contextual checking for ThisType?