Is "This" sufficient as the return type in TypeScript?

During my experimentation with method chaining, I discovered that it is possible to use "this" as a return type. How interesting!

Let's take a look at 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);

Check out the example on the playground

Could this be the right approach for achieving method chaining when dealing with base and inherited classes?

Answer №1

Utilizing polymorphic references like this can greatly simplify the creation of fluent APIs, as all subtypes seamlessly interact with the reference type. For more information, refer to the Advanced Types section and explore the concept of F-bounded polymorphism.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does the for..in loop not function properly when executing a script with ts-node?

Check out ./src/repro.ts class P { do() { console.log('d'); } } const x = new P(); console.log('for in:'); for (const key in x) { console.log(key); } I'm using this configuration file ./tsconfig.json to compile it (tried ...

Tips for creating a console.log wrapper specifically designed for Angular2 using Typescript

Is there a way to create a custom global logging function in Angular 2 TypeScript project that can be used instead of console.log for services and components? I envision the function looking like this: mylogger.ts function mylogger(msg){ console.log ...

Establishing specific categories for a universal element

I have been working on creating an input component that functions as a custom select for enums in my application. I have tried defining them for different types using concise one-liners but have run into various typing issues. Here is what I have so far: ...

Creating a personalized snippet in VSCode for inserting GraphQL tags or strings in a TypeScript file

Currently, I am constructing an API in Graphql utilizing ApolloServer and Apollo Subgraphs. My codebase is written in TS, however, to take advantage of the subgraph functionality, I must enclose my schema with gql. For example: import { gql } from 'ap ...

CRITICAL ISSUE: Mark-compact processes not performing effectively close to heap capacity

I encountered an error and I'm seeking a brief explanation to help me understand what needs to be fixed. This error occurs during the compilation of TypeScript. <--- Last few GCs ---> [1791:0x5533880] 72626 ms: Scavenge (reduce) 2042.8 (2 ...

When trying to use `slug.current` in the link href(`/product/${slug.current}`), it seems to be undefined. However, when I try to log it to the console, it is displaying correctly

import React from 'react'; import Link from 'next/link'; import { urlFor } from '../lib/clients'; const Product = ({ product: { image, name, slug, price } }) => { return ( <div> <Link href={`/product/ ...

Unable to substitute a sub-string containing brackets in a string array using TypeScript/JavaScript

So I have this string that says: My column name is Start Date (GMT). What I want to do is replace the portion "Start Date (GMT)" with "start_date". I've been attempting to achieve this using the following code: let a= "My column name is Start D ...

What steps should be taken when encountering an error with fs while using ANTLR?

I have encountered an issue with antlr while using Angular in Visual Studio Code. I am familiar with including and writing a grammar in a project, but recently I ran into a problem when starting it: "ERROR in ./node_modules/antlr4/CharStreams.js Module no ...

AngularJS is failing to properly register custom directives

Looking to enhance the SEO caching capabilities of my AngularJS website, I've embarked on implementing a couple of directives for custom page titles and descriptions. Incorporated within my app config (angular.module('website', [...'we ...

Why am I unable to use a string as the src in next/image component?

After importing the Image module with the code import Image from "next/image";, I encountered an error that states: The type '{ src: string; }' cannot be assigned to type 'IntrinsicAttributes & ImageProps'. The type &apo ...

Is there a way to programmatically close Chrome that is running in Kiosk mode?

Currently, I am facing an issue with my Angular 9 app running in Chrome within a Kiosk mode environment. I urgently require a solution to close the Chrome browser as there is no keyboard attached to the PC handling the app. Is there a way to achieve this ...

Passing public field names with typed expressions in TypeScript

I've been exploring ways to pass an array of property names (or field names) for a specific object without resorting to using what are often referred to as "magic strings" - as they can easily lead to typos! I'm essentially searching for somethin ...

Ensure that the database is properly configured before running any test suites

Currently, I am facing the challenge of seeding my database with all the necessary resources required to successfully test my API. These tests are spread across multiple files. Is there a method that will allow me to fully seed the database before any tes ...

Trouble with setState function within constructor in ReactJS

Running the code below in React+Redux is proving to be a challenge as I keep encountering an unhandled exception 'NodeInvocationException: Cannot read property 'showText' of null TypeError: Cannot read property 'showText' of ...

Utilizing Zod for Recursive types and accurately inferring them

Here are my schemas: export const barSchema = z.object({ id: z.string(), foo: z.object(fooSchema), }); export const fooSchema = z.object({ id: z.string(), bar: z.object(barSchema), }); export type BarType = z.infer<typeof barSchema>; My ch ...

In Firefox, xPath is failing to evaluate

I am encountering an issue with the document.evaluate function when attempting to validate xPath in Firefox. The document.createNSResolver function seems to be malfunctioning as I only receive xmlDoc and nothing else. Even when I try leaving it with a null ...

What could be the reason for TypeScript inferring the generic type as an empty string?

I have developed a React component known as StateWithValidation. import { useStateWithValidation } from "./useStateWithValidation"; export const StateWithValidation = () => { const [username, setUserName, isValid] = useStateWithValidation( ( ...

A step-by-step guide on extracting information from a component and using it within a Guard

A challenge I am facing is how to display a warning prompt on the screen if the user tries to leave a page after making changes to a form. I have successfully created a Guard that logs a message to the console when the user attempts to navigate away from t ...

Error: The selected module is not a valid top-level option

I am facing an issue while using the babel-loader. I have removed all irrelevant code and just kept the error-related portion. What could be causing this problem? module.exports = merge(baseWebpackConfig, { ... module: { rules: [ ...

Can the child component ensure that the Context value is not null?

In the process of developing a Next.js/React application with TypeScript, I've implemented a UserContext in pages/_app.js that supplies a user: User | null object to all child components. Additionally, there's a ProtectedRoute component designed ...