How do I safely convert a Typescript object
to Record<PropertyKey, unknown>
? For example, when reading JSON you get an any
object which should really be unknown
(I assume it isn't for backwards compatibility):
const ob = JSON.parse("{}") as unknown;
I can convert the unknown
to an object
using a type assertion:
if (typeof ob !== "object" || ob === null) {
throw new Error("Not an object");
}
// Typescript now infers the type of ob as `object`
But what check do I now do to convince Typescript that it is safe to treat it as Record<PropertyKey, unknown>
? Is it possible that there are object
s that aren't Record
s?
I'm sure it has to be said, but I am not looking for ob as Record<PropertyKey, unknown>
.