io-ts
io-ts copied to clipboard
Allow Error to be decoded with UnknownRecord
Some libraries (e.g. AWS SDK, Axios) will throw Errors, but won't export the actual Error itself which prevents an e instanceof XError check.
It's useful to be able to write a codec for these Errors, but no longer works after 2.0.5 (previous implementation).
Related to issue #485.
I'm running into this issue now, it was very surprising to find that UnknownRecord doesn't consider instances of Error to be compatible.
Concretely, the following returns false, where I believe it should return true:
t.type({}).is(new Error()); // false
Is there a compelling reason for why Error should not be included here?
I also ran into this issue, we switched to a fork with this PR applied which is working well so far.
The fix in this PR still allows some surprising behavior on weird objects though, since Object.prototype.toString can be customized like this:
const obj = { [Symbol.toStringTag]: 'something' };
Object.prototype.toString.call(obj); // '[object something]'
It looks like the original intention of the change in 2.0.5 was just to exclude arrays from UnknownRecord. The most reliable way to do that is probably to exclude arrays explicitly, rather than trying to build a list of non-array types that are allowed. For example, with Array.isArray:
u !== null && typeof u === 'object' && !Array.isArray(u)
Fix: https://github.com/gcanti/io-ts/releases/tag/2.2.19