Type assertions not allowed:
Due to the design goal of type erasure (no runtime overhead), type assertions are not ever checked.
When you assert a type, it may look suspiciously like type casting in a language such as Kotlin, but it isn't the same thing. TypeScript just "trusts" you and doesn't check the type.
At runtime, you wouldn't get a cast error if the type is not the same, but only see a problem if you try to access or use a value that doesn't match the expected type.
Use parsing libraries such as zod.
type Foo = {
x: 1;
};
const foo = JSON.parse('{"y":1}') as Foo;
foo.x + 1;
const bar = JSON.parse('{"xyz":1}') as { x: { y: number } };
console.log(bar.x.y);
import * as z from 'zod';
const FooSchema = z.object({
x: z.number(),
});
type Foo = z.infer<typeof FooSchema>;
const foo = FooSchema.parse(JSON.parse('{"x":1}'));
const bar = FooSchema.parse(JSON.parse('{"y":1}'));