3 ms·
I 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
by charrondev 8y ago
I 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.