Enforcing TypeScript restrictions on method chaining during object creation

Let's consider this unique sample class:

class Unique {
  public one(): Pick<this, "two" | "three"> {
    return this;
  }
  public two(): Pick<this, "three"> {
    return this;
  }
  public three(): string {
    return "something else";
  }
}

With the above setup, we can perform the following actions:

const unique = new Unique();
unique.one().two(); // Allowed
unique.two().one(); // Error: Property 'one' is not recognized on type 'Pick<Unique, "three">'.

The scenario outlined allows me to select which methods are chainable in the class, but I wonder if it's feasible to do so from the base of the class instance. In other words, is there a way for TypeScript to enforce that only the base can access the method one, and restrict access to any other methods?

For example:

const unique = new Unique();
unique.one(); // Allowed
unique.two(); // Error: Property 'two' does not exist on type 'Unique'.
unique.three(); // Error: Property 'three' does not exist on type 'Unique'.

Any assistance on this matter would be greatly appreciated.

Answer №1

By using a return type of asserts this is, you can modify the type of the class instance. Here's an example to demonstrate:

class Sample {
  public doSomething(): asserts this is Record<"key", never> {
  }
  public anotherMethod() {
  }
}

const sample: Sample = new Sample();
sample.doSomething(); // success
sample.anotherMethod(); // failure

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

The .slice() function in TypeScript has the ability to alter the initial array

I am diving into TypeScript and just tackled my first slice() method. My understanding is that the slice() method is supposed to create a copy of an array. Here's a snippet of the code: class ChapterOne { // Gauss Jordan Elimination // No ...

"Angular 2: Organize and refine data with sorting and

Sorting and filtering data in Angularjs 1 can be done using the following syntax: <ul ng-repeat="friend in friends | filter:query | orderBy: 'name' "> <li>{{friend.name}}</li> </ul> I have not been able to find any ex ...

typescript decorator implemented on a class that is nested within another class

Is it possible to decorate a nested property within a class? Let's explore with an example: function log(name: string = 'DecoratedProp') { return function logHandler(target: any, field: any) { // get the key ...

Implementing Express.js allows for the seamless casting of interfaces by the body within the request

I have created a similar structure to ASP.NET MVC and uploaded it on my github repository (express-mvc). Everything seems fine, but I am facing an issue with casting the body inside the request object to match any interface. This is what I am aiming for: ...

Resolving the issue of missing properties from type in a generic object - A step-by-step guide

Imagine a scenario where there is a library that exposes a `run` function as shown below: runner.ts export type Parameters = { [key: string]: string }; type runner = (args: Parameters) => void; export default function run(fn: runner, params: Parameter ...

What is the best way to update an array in TypeScript when the elements are of different types and the secondary array has a different type as

const usersData = [ { "id": 0, "name": "ABC" }, { "id": 1, "name": "XYZ" } ]; let dataList = []; // How can I transfer the data from the user array to the dataList array? // If I use the map function, do I need to initialize empty values for oth ...

Issues encountered when attempting to use Angular2 with SystemJs and typescript transpiler

I've encountered an issue with my TypeScript transpiler setup. My @angular component isn't loading, and I'm getting this error message: ZoneAwareError: "Error: core_1.Component is not a function Evaluating http://127.0.0.1:64223/app/app.c ...

Transmit information from child to parent as needed using @input and @output in Angular 2

Is there a way to pass an object from child to parent without relying on @viewChild or services? export class MultiSelectComponent implements OnInit { selectedItems: FormSelectComponentOption[] = []; @Input() items: FormSelectComponentOption[]; @Output ...

React JS displayed the string of /static/media/~ instead of rendering its markdown content

When I looked at the material UI blog template, I created my own blog app. I imported a markdown file using import post1 from './blog-posts/blog-post.1.md'; Next, I passed these properties to this component like so: <Markdown className=" ...

using the ts-migrate-mongoose package for migrating MongoDB

I'm currently working on a NestJS application and using ts-migrate-mongoose for database migration. The issue I'm facing is related to importing a user schema from outside of the migration folder (which is located in the root folder by default). ...

What is the best way to transform this component into a function rather than a class?

import React, { Component } from "react"; class ChatHistory extends Component { render() { const messages = this.props.chatHistory.map((msg, index) => ( <p key={index}>{msg.data}</p> )); return ( <div ...

How to modify the background color within the mat-menu-panel

Incorporating angular 9 and less into my current project, I have encountered an issue with a mat-menu-panel where my mat-menu-item is located. While I have successfully changed the color of my mat-menu-item, I am now faced with the challenge of changing th ...

Utilizing raw queries in TypeORM with NestJS to enforce lowercase column names

Can anyone help me execute a query using nest/typeorm? I'm utilizing Typeorm's "InjectConnection" to run a raw query in my Postgres Database. The issue arises with the column user_roles_role.userId (note that I am specifying 'userId' i ...

Unexpected token error on an optional property in Visual Studio Code

I encountered a problem with a project I cloned. Below is the code snippet created using this project: https://github.com/enuchi/React-Google-Apps-Script export interface Vehicle { wheels: number; insurance?: string; } export default class Car { whe ...

The issue arose as a result of a SQLITE_ERROR, specifically mentioning that the Users table does not exist. However, the model has been

Greetings! I am currently facing an issue while trying to integrate the "sequelize-typescript" library into my Express.JS REST API that I developed using Dependency Injection. The error I am encountering is: SQLite Error: no such table: Users Below is th ...

JavaScript/Typescript is throwing an error because it is unable to access the property 'username' of an undefined object

In my project, I am attempting to compile a list of Profile objects and then extract specific elements from each object in the list. To accomplish this, I have defined a public interface named Profile, imported it into my component, and instantiated a new ...

'value' is connected to every single hook

Every time I try to save my work using any hook, the 'value' field changes automatically. This has been causing me a great deal of stress. I would be extremely grateful if someone could assist me with this issue. click here for image description ...

Steps for assigning a parameter to a general purpose function

Having a generic function named retrieve: function retrieve<T>(endpoint: string, id: string, /* etc */): T {} The goal is to define a function like retrieveUser, which binds the first parameter and specifies T. An attempt was made using Function.pr ...

Error: The script cannot be compiled with the '--isolatedModules' flag as it is recognized as a global script file

Currently, I am working on building my NextJS app and incorporating Cypress for testing along with Typescript. During this process, I encountered the following error: Type error: 'home.cy.ts' cannot be compiled under '--isolatedModules' ...

The number of keys in the related object must correspond to the length of the array in Advanced Generic Types

Can we achieve type safety across rows and columns by having one object define the structure of another? Starting Point: export interface TableColumn { name: string; type: "string" | "number" | "action"; id: string; } ...