Skip to main content

TypeScript as Type Assertion vs Pydantic Validation

as Type Assertion

Only tells the compiler "I believe this data looks like this" — performs zero validation:

const message = JSON.parse(rawJson) as TaskMessage;
// JSON.parse → converts string to JS object
// as TaskMessage → just tells TypeScript "treat this as this type"
// doesn't check the data, won't throw an error
rawJson = '{"taskId": "abc", "payload": {...}}'

JSON.parse → { taskId: "abc", payload: {...} } ← plain JS object, no validation

as TaskMessage → TypeScript compiler believes it has taskId and payload fields
but if it actually doesn't, it only blows up at runtime

Pydantic (Python)

Actually validates the data — throws an error if the format is wrong:

class TaskMessage(BaseModel):
taskId: str
payload: Payload

# Validates! Missing fields or wrong types immediately raise ValidationError
message = TaskMessage.model_validate(json.loads(raw_json))

Comparison

TypeScript asPydantic
Validates dataNoYes
Runtime protectionNoneYes
EffectJust stops the compiler complainingActually ensures data is correct
AnalogySticking a label (ignores contents)Going through security (rejects non-conforming data)

Want Pydantic-like Validation in TypeScript? Use zod

import { z } from "zod";

const TaskMessageSchema = z.object({
taskId: z.string(),
payload: PayloadSchema,
});

// This actually validates, similar to Pydantic
const message = TaskMessageSchema.parse(JSON.parse(rawJson));

When to use as vs zod?

ScenarioRecommendation
Message is from your own system, format is trustedas is sufficient
Data from external API, user inputUse zod for validation