'Union 'this' type with original 'this' type?
In typescript, I can specific this type like this:
let data = {
prop1: "prop1"
}
let obj = {
fun1(this: typeof data){
this.prop1; // works
this.fun2(); // doesn't work
},
fun2(){}
}
But how can I declare 'this' type that I can make union with original 'this' type so I can write like this.fun2(), maybe something like fun1(this: typeof _this | typeof data).
Solution 1:[1]
I think you're looking for something like this:
let data = {
prop1: "prop1",
};
interface ObjType {
fun1(this: (typeof data) | ObjType): void;
fun2(): void;
}
let obj: ObjType = {
fun1(this: (typeof data) | ObjType) {
if ("prop1" in this) {
this.prop1; // works
}
if ("fun2" in this) {
this.fun2(); // works
}
},
fun2() {
}
}
(We need the type declaration because we can't use typeof obj in obj's constructor if we don't have a type on it. Well, we can, but we get any.)
Note the need for type guards, because this could be typeof data (and so have prop1) or ObjType (and so have fun2). So we have to figure out which it is before using them.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | T.J. Crowder |
