ts-optchain
ts-optchain copied to clipboard
Add then() hook which returns null
Hi.
This line: https://github.com/rimeto/ts-optchain/blob/734afe9c258e0cbd68b41178e445f21dc187281c/src/proxy/index.ts#L17
The essence is that oc() object cannot be currently returned as a Promise (see StackOverflow link below).
So to work-around, I had to wrap the oc() proxy into one more proxy which says that there is no then() hook defined explicitly:
async json<TRes>() {
const json = await (await this.fetch()).json();
const ocProxy = oc(json as TRes);
// This is crazy, but no-one can return Promise<Proxy> and live...
// Because await calls Proxy's then() hook which doesn't exist in oc().
// https://stackoverflow.com/a/53890904
return new Proxy(ocProxy, {
get: (target, key) => (key == "then" ? null : (target as any)[key])
}) as typeof ocProxy;
}
...
const res = await obj.json<{xyz: string}>();
console.log(res.xyz()); // hangs if json() doesn't do the trick and just returns the oc()
There could be a simple fix to oc() by just checking key
for "then"
- the same way as in the example above.
I was about to create a similar ticket, returning oc from a promise breaks the promise. Maybe something with a condition like data instanceof Promise
.