What is TypeScript?
TypeScript is JavaScript with a type system added on top. It’s a
superset of JavaScript — every valid JS file is also valid TypeScript — but
it lets you declare data types so the compiler can catch mistakes before
the code runs, instead of at runtime. This site (and its .astro
components) are written in TypeScript.
The problem it solves
Plain JavaScript doesn’t check types, so mistakes like a mistyped field,
passing the wrong argument type, or forgetting to handle null only surface
when the code actually runs — or worse, once it’s already in production.
TypeScript catches most of these while you’re still writing the code, right
in the editor.
Basic syntax
// Type-annotate variables, parameters, return values
function greet(name: string): string {
return `Hello, ${name}`;
}
// Interface / type describing an object's shape
interface Post {
title: string;
pubDate: Date;
tags: string[];
}
// Union type — a value that can be one of several types
type Locale = "en" | "vi";
Type inference
You don’t always need explicit annotations — TypeScript infers types from the assigned value:
const count = 3; // TypeScript infers this as number
Why it’s used here
- Astro Content Collections use Zod schemas to validate Markdown
frontmatter and auto-generate types for
post.data.title,post.data.pubDate, etc. — a typo in a field name fails at build time, not after the site is already deployed. - Shared helpers like
src/lib/content.tsdeclare explicit types (Locale,CollectionEntry<"blog">…), giving accurate autocomplete when writing new components. npm run buildalways runsastro checkfirst — a type error stops the build instead of silently shipping broken code.
When TypeScript pays off
For a tiny, single-file script, plain JS is fine. But as code grows, more people touch it, or data flows through several layers (Markdown → component → render), the type system catches a lot of small bugs that would otherwise only show up by clicking through the site manually.
Further reading
Official docs: typescriptlang.org/docs