4 ms·
> I very rarely see TypeScript developers actually use `any` (usually to reflect something like something parsed from arbitrary JSON that needs to be interrogat
by dvlsg 8y ago
> I very rarely see TypeScript developers actually use `any` (usually to reflect something like something parsed from arbitrary JSON that needs to be interrogated rather than just type-asserted)
Even that example usage of `any` should be less common, now. I think `unknown` (which is fairly new) is better there.
- Zarel 8y agoIs it? My impression is that `unknown` type doesn't solve that specific problem. const out: unknown = JSON.parse("{a: 1}"); if (out && typeof out.a === 'number') console.log(out.a); gives the error: [ts] Object is of type 'unknown'. [2571]
- charrondev 8y agoPretty sure you’re missing a typeof check for ‘out’.
- Zarel 8y agoI'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.