简体   繁体   中英

What does <this> mean in TypeScript generics?

We use express with TypeScript in our app. I came across their type definitions and was wondering what the following means:

export interface IRouter extends RequestHandler {
    all: IRouterMatcher<this>;
}

在此处输入图片说明

In particular, the IRouterMatcher<this> .

I read the docs a few times and couldn't find anything mentioning this use case. And it's pretty hard to search for <this> in either SO or the web as the angle brackets usually get stripped.

this refers to the current available type.

This might also be the subtype of the overridden class or interface.

See also Polymorphic this types in https://www.typescriptlang.org/docs/handbook/advanced-types.html

Example:

class Calculator {
    a: number;
    add(): this {
        a++;
        return this;
    } 
}

class AdvancedCalculator {
    substract(): this {
         a--;
         return this;
    } 
}

new AdvancedCalculator()
   .add() // returns AdvancedCalculator as "this" 
   .substact() // it compiles! 

I believe <this> , in your example, refers to the type that is currently implementing the interface. For example if a class named TestClass implemented IRouter, then the functions that return IRouterMatcher<this> would return an IRouterMatcher<TestClass> .

After doing some more research, using <this> might be functionally equivalent to saying <T extends IRouter> such as all: IRouterMatch<T extends IRouter> . Using this might just be a shorter way to express the same thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM