Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"This" used as return type in TypeScript?

Tags:

typescript

I was testing out method chaining and found that it can be accomplished using "this" as a return type?

Here's an example:

class Shape {
    color: String;

    setColor(value: string): this { //Shape won't chain
        this.color = value;
        return this;
    }
}

class Square extends Shape {
    width: number;

    setWidth(value: number): Square {
        this.width = value;
        return this;
    }
}

function drawSquare(square: Square) {
    alert("width: " + square.width + "\ncolor: " + square.color);
}

let rect = new Square().setWidth(20).setColor("blue");
drawSquare(rect);

Example in playground

Is this the correct way of achieving method chaining when mixing base and inherited classes?

like image 305
Jeremy Robson Avatar asked May 23 '16 21:05

Jeremy Robson


People also ask

What is return type in TypeScript?

To define the return type for the function, we have to use the ':' symbol just after the parameter of the function and before the body of the function in TypeScript. The function body's return value should match with the function return type; otherwise, we will have a compile-time error in our code.

How do you get a return type of function in TypeScript?

Use the ReturnType utility type to get the return type of a function in TypeScript, e.g. type T = ReturnType<typeof myFunction> . The ReturnType utility type constructs a type that consists of the return type of the provided function type.

What is this in TypeScript?

Introduction. One of the most important concepts to grasp in TypeScript is the use of the "this" keyword, which is used in object methods. The "this" keyword always points to the object that is calling a particular method.

How do you define return type in Arrow TypeScript?

Set the return type of an arrow function in TypeScript # You can set the return type of an arrow function in TypeScript right after its parameters, e.g. const greet = (name: string): string => {} . Once a function's return type is set, the type checker alerts us if the function returns a value of a different type.


1 Answers

Surely, using polymorphic this makes fluent api's very easy to express as any subtypes 'flow' with the this type. Check the Advanced Types section, and F-bounded polymorphism.

like image 72
krontogiannis Avatar answered Oct 07 '22 12:10

krontogiannis