TypeScript Basics
Before diving into advanced types, you need a grasp of how TypeScript files are structured, how types attach to values, and how the compiler fits into your workflow.
TypeScript Basics Overview
TypeScript basics mirror JavaScript syntax while adding type annotations, interfaces, and compile-time validation. A typical file declares typed variables, functions, and imports modules just like modern ES modules.
Understanding the relationship between .ts source files and compiled .js output is essential. The compiler erases types at build time—they exist only during development.
| Building Block | Purpose | Example |
| Type annotations | Declare expected shapes | let count: number = 0 |
| Functions | Typed inputs and outputs | function add(a: number, b: number) |
| Interfaces | Describe object contracts | interface User { name: string } |
| Modules | Organize and share code | export / import |
| tsc | Compile TS to JS | npx tsc |
TypeScript Basics Example
let productName: string = "Keyboard";
let price: number = 79.99;
let inStock: boolean = true;
function formatPrice(name: string, amount: number): string {
return `${name}: $${amount.toFixed(2)}`;
}
console.log(formatPrice(productName, price));
Variables receive explicit primitive types, and the function declares both parameter and return types. If you pass a string to price, the compiler reports an error immediately.
When to Use TypeScript Basics
- Learning TypeScript for the first time
- Setting up your first typed function or variable
- Reviewing how TS syntax maps to JavaScript
- Onboarding teammates to a typed codebase
- Preparing for interfaces and generics later
- Writing small scripts with type safety
Best Practices
- Use const by default and let when reassignment is needed
- Annotate function return types on exported APIs
- Prefer interfaces for object shapes you reuse
- Compile frequently to get fast feedback
- Keep one concept per example while learning
- Read compiler error messages—they are usually precise
- Use strictNullChecks to avoid null-related bugs
Common Mistakes to Avoid
- Annotating every local variable unnecessarily
- Forgetting that types disappear after compilation
- Mixing default and named exports inconsistently
- Using var instead of let or const
- Ignoring unused variable warnings
- Treating TypeScript as a completely different language
- Skipping module resolution configuration
Key Takeaways
- TypeScript syntax builds on modern JavaScript
- Types are checked at compile time only
- Functions, variables, and objects can all be typed
- The compiler outputs standard JavaScript
- Basics prepare you for interfaces and generics
- Good habits early reduce pain in large projects
Pro Tip
When stuck on a type error, hover the variable in VS Code and read the inferred type. Often the fix is aligning your annotation with what the compiler already knows.