My goal is to find a way to use the this
type or something similar outside of a class or interface method in TypeScript, rather than being limited to just within a class or interface.
Consider this example:
class TypedArray {
[index: number]: number;
length: number;
static of(...args: number[]): this {
console.log(this);
return new this(args);
}
static from(args: number[]): this {
console.log(this);
return new this(args);
}
constructor(args: number[]) {
for (let i: number = 0; i < args.length; ++i) {
this[i] = args[i];
}
this.length = args.length;
}
}
class Int32Arr extends TypedArray {
forEach(callback: (n: number) => unknown): void {
for (let i = 0; i < this.length; ++i) {
callback(this[i]);
}
}
constructor(args: number[]) {
super(args);
console.log("Subclass contrustor called!");
}
}
const x: Int32Arr = Int32Arr.of(0, 1);
console.log(
x,
x instanceof Int32Arr
);
In this code snippet, it's important to note that when using this
, it actually references the subclass Int32Arr
instead of TypedArray
.
As a result, x
is considered an instance of Int32Arr
, not TypedArray
.
I am seeking a way to make TypeScript Compiler (TSC) understand and handle this scenario correctly. Any suggestions on how to achieve this?