3 ms·
I'm pretty sure I'm not. const out: unknown = JSON.parse("{a: 1}"); if (typeof out === 'object' && out && typeof out.a === 'number') { console.lo
by Zarel 8y ago
I'm pretty sure I'm not.
const out: unknown = JSON.parse("{a: 1}");
if (typeof out === 'object' && out && typeof out.a === 'number') {
console.log(out.a);
}
gives the error:
[ts] Property 'a' does not exist on type 'object'. [2339]
It's a completely unnecessary check, anyway: `out &&` is sufficient to exclude `null` and `undefined`, which is all that's needed to ensure that `out.a` won't crash. I challenge you to give a single input to `JSON.parse` that would crash my code without the `typeof` check.
- charrondev 8y agoI see what you mean. I guess unknown just doesn't work that well with inline type checks for objects, although in that case you probably want a function anyways. Using the `in` return type you can do something like this: const out: unknown = JSON.parse("{a: 1}"); interface MyStructure { a: number; } function isMyStructure(toCheck: unknown): toCheck is MyStructure { return toCheck instanceof Object && 'a' in toCheck; } if (isMyStructure(out)) { console.log(out.a); } This will give you no type errors, and gives you the benefit of having a re-usable function for this validation. I just discovered this today. I seem to have missed it in a recent release note.
- Zarel 8y agoOh, yeah, that feature's existed for years; it's called "user-defined type guards". https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards https://www.typescriptlang.org/docs/handbook/advanced-types.... Unfortunately, it doesn't work in `checkJs` mode, and I always wish I could do it inline.