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
CodePudding user response:
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));
