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