JSON.parse
returns any
type:
const obj = JSON.parse('{"a": "b"}')
How do I ensure the return value obj
has the expected type?
JSON.parse
returns any
type:
const obj = JSON.parse('{"a": "b"}')
How do I ensure the return value obj
has the expected type?
You can use a type guard, or more safely, use a type extractor:
interface MyType {
a: string;
}
function extractMyType(arg: unknown): MyType | null {
if (
typeof arg === "object" &&
arg !== null &&
"a" in arg &&
typeof arg.a === "string"
) {
return { a: arg.a };
}
return null;
}
const obj = extractMyType(JSON.parse('{"a": "b"}'));
if (obj === null) {
throw new Error("Not MyType");
}
console.log(obj);
//^? const obj: MyType
You may think why not just narrow the type after receiving the object returned by JSON.parse
. This is because type narrowing right after retrieving the result of parsing often doesn’t work due to a limitation in TypeScript:
interface MyType {
a: string;
}
const obj: unknown = JSON.parse('{"a": "b"}');
if (
typeof obj === "object" &&
obj !== null &&
"a" in obj &&
typeof obj.a === "string"
) {
obj;
//^? const obj: object & Record<"a", unknown>
}