I have a function which takes objects and proxies them.
I do not want it to proxy classes, and I'd like to assert that with the argument type.
How can I do this?
type NonClassObject = ???;
export function createObjectProxy(obj: NonClassObject) {
return new Proxy(obj, {});
}
const foo: NonClassObject = {};
const bar: NonClassObject = {} as HTMLElement; // this should be a type error
There doesn't seem to be much to distinguish the two except for the typeof the constructor. I'm not sure if there's a way to say Exact<tyepof OBJ.constructor, Object>
... but I'm looking into Utility types now.
Dead end: https://github.com/Microsoft/TypeScript/issues/3841
There's an open issue about making the constructor type more defined (https://github.com/Microsoft/TypeScript/issues/3841) but it's 4 years old and not seeming to get anywhere.
As a stopgap solution, I've just started adding { _noMyProjectProxy: true }
to all my classes, and listing out anything I don't have access to. It looks like this:
type NonClassObject<TYPE> =
TYPE extends HTMLElement ? never :
TYPE extends Event ? never :
TYPE extends OtherClass ? never :
TYPE extends { _noMyProjectProxy: any } ? never :
TYPE;
export function createObjectProxy<TYPE extends object>(obj: NonClassObject<TYPE>) {
return new Proxy(obj, {});
}
It's not pretty or elegant, but it works when nothing else did.