Basic ThisType<T> Syntax
What you'll learn: How to use the ThisType<T> utility type in an intersection with an object type to explicitly control what this refers to inside methods.
The Core Idea
ThisType<T> is a special marker type that doesn't affect the runtime shape of your object, but tells TypeScript what type this should have inside methods. You use it by intersecting it with an object type:
type MyObject = {
data: string;
methods: {
doSomething(): void;
} & ThisType<{ data: string }>;
};
Here, ThisType<{ data: string }> tells TypeScript that inside doSomething, this should be typed as { data: string }, even though the method itself doesn't explicitly show that structure.
How It Works
Think of ThisType<T> like a type-level instruction manual for the compiler. When TypeScript sees it in an intersection, it reads: "Inside these methods, treat this as if it has type T."
The syntax pattern is:
{
// ... properties
} & ThisType<WhatThisShouldBe>
Simple Example
type Container = {
name: string;
helpers: {
greet(): string;
} & ThisType<{ name: string }>;
};
const obj: Container = {
name: "TypeScript",
helpers: {
greet() {
// TypeScript knows this.name exists and is a string
return `Hello, ${this.name}`;
}
}
};
Without ThisType, TypeScript wouldn't know that this inside greet has a name property—it would only see the helpers object structure.
Why the Intersection?
You must use & (intersection) because ThisType<T> doesn't define properties itself—it only annotates what this should be. The object type defines the actual method signatures, and ThisType adds the context information.
Key Takeaway: ThisType<T> is used in an intersection (& ThisType<...>) to tell TypeScript what type this has inside methods, without changing the actual object structure.