TypeScript Basics
From SCRUM-14: Learn what is TypeScript
My Learning Notes
TypeScript is like a compiler for JavaScript language. It catches type errors before the code even runs in the browser. The
tsconfig.jsonis defined in the root folder and includes multiple fields to define the behavior of the compiler.
Key Insights
- TypeScript is applied to the entire codebase - we can specify which version of JS to compile to, so we don't have to worry about browser support
- IDE catches errors while writing - don't have to wait until running in browser
- Default types can be implicit or explicit - declared with
: type_name - We can use latest JS features while writing
.tsfiles, and old browsers can still understand the compiled code
What is TypeScript?
TypeScript is a superset of JavaScript that adds static typing:
- All valid JavaScript is valid TypeScript
- TypeScript adds type annotations
- Types are checked at compile time, not runtime
Why Use TypeScript?
- Catch errors early - Find bugs before running code
- Better IDE support - Autocomplete, refactoring, inline errors
- Self-documenting - Types explain what code expects
- Safer refactoring - Compiler catches breaking changes
- Browser compatibility - Compile to any JS version
Basic Types
// Primitives (always lowercase!)
let name: string = "Katie";
let age: number = 25;
let isLearning: boolean = true;
// Arrays
let words: string[] = ["hello", "world"];
let numbers: Array<number> = [1, 2, 3];
// Objects
let user: { name: string; age: number } = {
name: "Katie",
age: 25
};
Important
Always use lowercase primitive types: string, number, boolean
Never use String, Number, Boolean (these are object wrappers)
Type Inference
TypeScript can often figure out types automatically:
// TypeScript knows this is a string
let message = "Hello";
// TypeScript knows this is a number
let count = 42;
// TypeScript knows this returns a number
function add(a: number, b: number) {
return a + b;
}
The any Type
You can opt out of type checking with any:
let flexible: any = "hello";
flexible = 42; // No error
flexible = true; // No error
warning
Avoid any when possible - it defeats the purpose of TypeScript!
tsconfig.json
The TypeScript compiler is configured via tsconfig.json:
{
"compilerOptions": {
"target": "ES2020", // JS version to compile to
"module": "ESNext", // Module system
"strict": true, // Enable strict type checking
"outDir": "./dist" // Output directory
},
"include": ["src/**/*"]
}
Key Takeaways
- TypeScript = JavaScript + Types + Compiler
- Types catch bugs at compile time (before browser)
- IDE shows errors as you type
- Use lowercase primitive types (
string, notString) - Can compile to any JS version for browser compatibility