Determining the type of <this> in an Object extension method using TypeScript

I am attempting to incorporate a functionality similar to the let scope function found in Kotlin into TypeScript.

My current strategy involves using declaration merging with the Object interface. While this approach generally works, I find myself missing the type information of the argument for the inner method (Refer to the example below).

Is there a way to deduce the type of the Object on which the function was invoked?

interface Object {
  let: <S>(block: <T = this>(thisVal: T) => S) => S | null
}

Object.prototype.let = function <T, S>(block: (thisVal: T) => S): S | null {
  return this != null ? block(this as T) : null
}

const a = {foo: 42}
// prefer not to write this -> 'a.let<typeof a>(it => console.log(it.foo));'
a.let(it => console.log(it.foo)); // type of 'it' is T = Object

Test it out on TS Playground

Answer №1

To achieve this functionality, you can include a `this` parameter in the `let` function and capture the value of `this` from the `let` call:

interface Object {
  let: <S, T>(this: T, block: (thisVal: T) => S) => S | null
}

Object.prototype.let = function <S, T>(this: T,  block: (thisVal: T) => S): S | null {
  return this !== null ? block(this as T) : null
}

const exampleObj = {foo: 42}
exampleObj.let(it => console.log(it.foo));

Check out the code on TypeScript Playground.

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

Executing a function within JSX to dismiss a modal in NextJS

I am currently utilizing the Tanstack React Query library to perform a POST request from a Modal that includes a form: const addDay = (day: TDay) => { const apiURL = process.env.NEXT_PUBLIC_SERVER_URL const queryURL = apiURL + router ...

Experience the impact of a lagging network connection on Chrome extensions through the power of React-NextJS

I'm currently working on a Chrome extension that requires me to limit download speeds in the browser programmatically (client-side). Despite researching extensively on the subject, I have not been able to find any information on how to achieve this us ...

New example of how to use the "useSession" syntax in Next Auth

Currently, I am delving into the next-auth documentation and feeling perplexed by the syntax used in the useSession hook. The way it's showcased in the documentation is as follows: const { data: session, status } = useSession() My confusion stems f ...

How can I configure Material-UI's textfield to return a numerical value instead of a string when the type is set to "number"?

Utilizing Material-UI's TextField alongside react-hook-form to monitor inputs has raised an issue for me. I have observed that regardless of the input type, it always returns a string. This creates conflicts with the data types I am using in my codeba ...

Displayed in the xmlhttp.responseText are the tags

Why do tags appear when I input xmlhttp.responseText into my textbox? It displays <!DOCTYPE html><html><body></body></html> along with the desired content. Is there a way to prevent the tags from being displayed? Here is the ...

javascriptJQuery validation function triggers JSF ajax request

I am currently experiencing a challenge with JSF ajax requests and jQuery events. I am using a jQuery event to validate a section of a form like this: jQuery(".btnNextStep").live("click", function(e) { var error = !validate(id); ... ...

Exploring TypeScript and React Hooks for managing state and handling events

What are the different types of React.js's state and events? In the code snippet provided, I am currently using type: any as a workaround, but it feels like a hack. How can I properly define the types for them? When defining my custom hooks: If I u ...

Having trouble setting up npm package (fsevents) on Mac OS Catalina?

I'm facing an error when trying to run the npm install express --save command. Can someone assist me in resolving this issue? The error message is as follows: > email@example.com install /Users/delowar/Desktop/ytdl/node_modules/chokidar/node_modu ...

Ways of invoking a component method from a service in Angular 2

I have a concept for creating a unique service that is capable of interacting with one specific component. In my application, all other components should have the ability to call upon this service and then have it interact with the designated component in ...

How to show specific images by clicking on particular items in Ionic 3 on a separate page

Can someone assist me with displaying specific images from a slider gallery? I am struggling to figure out how to show only the January edition when clicking on it in eighteen.html, while hiding the February and March editions. It has been 2 days of unsucc ...

concerning a snippet of programming code

I'm new to coding and I'd like some help understanding this piece of code, particularly the red colored fonts. Which page value are they referring to? $(function() { $("#title").blur(function() { QuestionSuggestions(); }); }); funct ...

Update to using res.get() instead of res.getHeader()

Looking for assistance with the code snippet below: const compress = require('compression'); export const handleCompression = compress({ filter: function (req: express.Request, res: express.Response) { return (/json|text|javascript|css|fo ...

The identifier "id" is not a valid index for this type

The code snippet below demonstrates the similarities and differences between the functions addThingExample2 and addThing. While addThingExample2 directly uses the union type Things, addThing utilizes a generic parameter THING extends Thing. The expression ...

Losing authentication token when refreshing with Nuxt asyncData and Axios

While testing a get API that retrieves an array of mail data through Postman, everything seems to be working smoothly. However, when I implement the asyncData method to fetch the array in my code, it only works once. Upon page refresh, I encounter a 401 er ...

Show labels for data on a circular graph using angular-chart.js

I recently created a pie chart using angular-chart.js and it's functioning smoothly. However, I'm facing an issue with displaying the data value on each section of the pie chart. My attempt to use Chart.PieceLabel.js by adding the code snippet b ...

Challenges with server side JavaScript in Nuxt.js, causing confusion with the framework

My partner and I are embarking on a website project for our school assignment, and we have opted to utilize Vue.js and Nuxt.js as the front-end frameworks, along with Vuesax as our chosen UI Framework. Despite our lack of experience with these tools and we ...

The encodeURIComponent function does not provide an encoded URI as an output

Looking to develop a bookmarklet that adds the current page's URL to a specific pre-set URL. javascript:(function(){location.href='example.com/u='+encodeURIComponent(location.href)}()); Even though when I double encode the returned URL usin ...

In Javascript, ensuring a stopping condition for a recursive function that is looping through JSON data

I am having trouble figuring out how to set the break condition for this recursive function. Currently, the function is causing the browser to freeze (seems to be stuck in an endless loop). My goal is to create a series of nested unordered lists based on ...

Error encountered while compiling a method within a .vue component due to a syntax issue

I have been closely following a tutorial on Vue.js app development from this link. The guide instructed me to add a login() function in the block of the Login.vue file. Here is the snippet of code provided: login() { fb.auth.signInWithEmailAndPa ...

Tips for incorporating the multiply times async function into mocha tests

I am attempting to utilize the async function foo multiple times in my mocha tests. Here is how I have structured it: describe('This test', () => { const foo = async () => { const wrapper = mount(Component); const button ...