Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
TypeScript: Infer type of <this> in Object extension method

I am trying to implement something similiar to the let scope function of kotlin in TypeScript.

My current approach is to use declaration merging with the Object interface. Which generally works but I'm lacking the type information of the argument for the inner method (See example below).

Is there a way to infer the type of the Object where the function was called on?

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}
// don't want 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

Try here on TS Playground

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can do this by adding a this parameter to the let function and capture 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 a = {foo: 42}
a.let(it => console.log(it.foo));

Playground Link

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!