What is TypeScript?
TypeScript is a strongly typed superset of JavaScript that compiles to plain JavaScript. Developed and maintained by Microsoft, it adds optional static typing and class-based object-oriented programming to the language.
Why TypeScript?
- Type Safety: Catch errors at compile time, not runtime
- Better IDE Support: Autocompletion, refactoring, navigation
- Self-Documenting: Types serve as inline documentation
- Scalability: Easier to maintain large codebases
- JavaScript Compatibility: All JavaScript is valid TypeScript
How TypeScript Works:
- Write TypeScript code (.ts files)
- TypeScript compiler checks for type errors
- Compiles to plain JavaScript
- JavaScript runs in any environment
TypeScript doesn't run directly - it's always compiled to JavaScript first. This means there's no runtime type checking, only compile-time.
Code Examples
TypeScript Basicstypescript
// Type annotations
let message: string = "Hello, TypeScript!";
let count: number = 42;
let isActive: boolean = true;
// Type inference - TypeScript figures out the type
let inferred = "I'm a string"; // TypeScript knows this is string
// Function with types
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Works
// console.log(greet(42)); // Error: Argument of type 'number' is not assignable
// Object type
interface User {
id: number;
name: string;
email?: string; // optional property
}
const user: User = {
id: 1,
name: "Alice"
};
console.log(user.name);TypeScript adds type annotations to JavaScript. The compiler checks that your code follows these type rules.
Quick Quiz
1. What does TypeScript compile to?
2. When does TypeScript check for type errors?
Was this lesson helpful?