TypeScript
Beginner
1 min read
TypeScript Compilation and the Type System
Example
// Structural typing — shape matters, not name
interface Point2D {
x: number;
y: number;
}
interface Coordinate {
x: number;
y: number;
}
// Compatible because shapes match
const pt: Point2D = { x: 1, y: 2 };
const coord: Coordinate = pt; // OK — same shape
// Excess property check (only on object literals)
// const bad: Point2D = { x: 1, y: 2, z: 3 }; // Error
// Type inference — no annotations needed here
const message = "Hello"; // string
const count = 42; // number
const items = [1, 2, 3]; // number[]
const double = (n: number) => n * 2; // (n: number) => number
// Widening — union returned from branches
function getStatus(code: number) {
if (code === 200) return "ok";
if (code === 404) return "not found";
return "error";
} // return type inferred as string
// Type erasure — compiled JS has no types
// TypeScript: const x: number = 5;
// JavaScript: const x = 5;
console.log(double(count)); // 84
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript