I use typescript v5.4.5 (playground) and have an issue. There is my code example
function wrapper<C>(ctx: any, fn: (r: any) => void) {
const r = {};
return fn.call(ctx, r);
}
class Example {
value!: number;
constructor(v: number) {
this.value = v;
}
getValue() {
return wrapper(this, function(r) {
r.value = this.value;
return r;
});
}
getValueWithArrowFn() {
return wrapper(this, (r) => {
r.value = this.value;
return r;
});
}
}
const e = new Example(9999);
console.log(e.getValue());
By logic, this code is fine and can run normally in javascript, because the Function.call
allow to call a function with a context, in this example is this
, a instance of Example.
The console will log: { value: 9999 }, it works in both javascript and typescript playground. But I don’t know how to let typescript know the type of this
in callback of wrapper in getValue
method. I have a solution that is to use Arrow Function, but this will make fn.call
meaningless.
I try to run this code, it works, but the type inference don’t. I want typescript knows what this
in callback (anonymous function) of wrapper in getValue
is.
You can see this here:
https://www.typescriptlang.org/play/?#code/GYVwdgxgLglg9mABAdwE4EMAOmCmqA8AwgHwAU0AHgFyLpgCeANIsGDaajXfQJSIC8xRADc4MACZ8A3gChE8xBAQBnKIlQDEUgL4BuOQtQ4oIVElYA6COgA2N8lArNUPfdpkyIN9MuWIAohToALaYNjhaBvLCtiA4AIQ0YCDBAEZ4+lGKKlCoINBwqKTCSSnpLpEKVYhQABYwyhYxNnGawvpV7lkA5sYAarE4pNJZVUYmZigY2HikdQ3MoJCwCBwj1RvqTYOa843NcR2bY8amSKhHG9quWV1VvVADLTgA6jB1AIKoqHDIAGJgYaVTbjM5TLC4Ip7ZhrARCWTHMbbZ67er7QaXRGgyYXUYKa6Y9xdJRgVSICL8RBgHDIAJBULhUgAThZTJunhUcHCFhscG6pBwFgeTziw1cQA
Nguyen Anh Tuan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.