Created
March 31, 2021 15:21
-
-
Save dmwyatt/b7f28f97faf4df73bae2e124d49c9915 to your computer and use it in GitHub Desktop.
[fakeBaseClass] Make it so TypeScript can handle Proxy traps in a constructor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://stackoverflow.com/a/51865579/23972 | |
function fakeBaseClass<T>(): new () => Pick<T, keyof T> { | |
return class {} as any; | |
} | |
// USAGE: | |
class FooProxy extends fakeBaseClass<Foo>(){ | |
private foo: Foo; // I would make this private as it is not really accessible on what the constructor of FooProxy returns (maybe remove it as I see no use for it) | |
constructor(foo: Foo) { | |
super(); | |
this.foo = foo; | |
let handler = { | |
get: function(target: FooProxy, prop: keyof Foo, receiver: any) { | |
if(Foo.prototype[prop] !== null) { | |
return target.foo[prop]; | |
} | |
return Reflect.get(target, prop, receiver); | |
} | |
} | |
return new Proxy(this, handler); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment