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

Axios - retrieving merchandise

I have created an endpoint that retrieves all product information in JSON format. I am attempting to display this data on my index.html page using Axios, but I am encountering difficulties with getting the data correctly. This is my first time working with ...

Unable to display information retrieved from an API within a React application

I am facing an issue with rendering questions fetched from an API. I have set up the state and used useEffect to make the API call. However, when I try to display the questions, it seems to disrupt my CSS and show a blank page. I even attempted moving the ...

Node JS application facing compatibility issues with Typescript not working as intended

I've been diving into Typescript and recently followed a tutorial on how to integrate it with an express api app. However, I encountered the following error: D:\Development\Node\Ed\TypeScript\src\app.ts:5 const app: Appl ...

Display when moving up and conceal when moving down

Is there a way to make the div appear when scrolling up and down on the page? I'm new to jquery and could use some assistance, please. ...

Utilizing Multi External CDN JavaScript File with Vue CLI Component: A Comprehensive Guide

I've been trying different methods to include external JS files in a Vue Component, such as using mounted() and created(), but unfortunately, none of them have worked for me so far. I'm not sure where I'm going wrong. Any assistance would be ...

Is there a method to determine the height of the viewport if the DOCTYPE is not specified in Chrome, Firefox, or Safari?

How can we accurately determine the viewport's height even if the DOCTYPE is not specified? When the DOCTYPE is missing, values that would typically be around 410 may instead show as 3016. Is there a solution for finding the viewport's height wi ...

What is the best approach to decipher an obfuscated JavaScript file?

While browsing a site, I came across a javascript file that appears like this: eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,Str ...

Parsing dates arriving from a Restful Service in JavaScript

When I make a Restful call, the JSON response contains dates in a strange format like this: /Date(-62135568000000)/ What is the simplest way to convert it to a normal date format like (January 10, 2016)? I have read some articles that suggest using rege ...

What is the reason behind material-ui's decision to invoke their dialogs twice?

After attempting to implement a modal and realizing the strange behavior, I switched to using a dialog instead. To my surprise, the issue persisted. This is how I approached it: import Dialog, { DialogProps } from '@material-ui/core/Dialog'; imp ...

Ways to customize the datetime-local format in an HTML input field

When dealing with the HTML input of datetime type, consider the following: Datefield: <input type="datetime-local" data-date="" data-date-format="DD MMMM YYYY, h:mm:ss"> The script below includes important code. $("input").val(moment().format(&apo ...

Extracting Vertices, Edges, Faces, and Triangles from GLB Model Using ThreeJS GLTFLoader

I am looking to incorporate basic information about the model into my model viewer. Specifically, I need to obtain the vertex, edge, face, and triangle count of the object, or at the very least, the vertex count. My attempted approach involves using the f ...

Challenges with browsing navigation in Selenium WebDriver

Recently, I began my journey of learning selenium WebDriver. In an attempt to automate the task of logging into an account using the Firefox browser, I encountered a discrepancy. Manually opening the browser and clicking on the login link from the homepag ...

Utilizing Javascript to set the innerHTML as the value of a form

I have written a JavaScript code that utilizes the innerHTML function, as shown below: <script> var x = document.getElementById("gps"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showP ...

Error: Unable to parse string in URI within vscode API

Console LOG displays: \Users\skhan\Library\Application Support\Code\User\summary.txt The loop is used to replace the slashes. It works fine in Windows but not in Ubuntu and Mac. This is an example on OSX 10.11.6. Howev ...

Encountering issues with gulp-angular-templatecache while processing angular templates through pipelining

I've encountered an issue with gulp-angular-templatecache in my gulpfile. Here's the task causing trouble: gulp.task('templates', function() { return gulp.src(paths.angularTemplates) .pipe(templateCache()) ...

What causes all the accordion panels to toggle simultaneously in a ReactJs application?

When I click on the + button in my accordion, all the sections open at once. What could be causing this issue? Here is my code: const questions = [ { id:1, question: 'What is React?', answer: 'React is a JavaS ...

Switching back and forth between celsius and fahrenheit using jQuery (my mistake in the code)

I am currently using Ajax to interact with the openweather API. Everything seems to be functioning correctly except for one issue. My goal is to create a button that toggles between displaying temperature in Celsius and Fahrenheit. When I click the button ...

The problem with the "typescript-react-apollo" codegen plugin is that it is declaring block-scope variables more than once in the generated

Recently, I embarked on a new project utilizing NextJS with graphql-codegen to auto-generate my apollo-react types from the API. Unfortunately, it seems to be generating duplicate exported variables right from the start, causing a typescript error and hi ...

CSRF fails to execute during the initial post submission

This is my first time dealing with CSRF and reaching out to Stack Overflow for the first time. After struggling through the configuration, I finally managed to get it working almost perfectly. However, I ran into an issue where if I open a bookmarked page ...

Retrieval of entity through REST Endpoint using ODataSetName for Custom Entity

In my restendpoint.js file, I have a function called retrieveRecord which is defined on this website I am working on a function that should trigger whenever the Programme (a lookup field) on the Application entity changes. The goal is to fetch the attribu ...