01-introduction.ts
Typescript/src/01-beginner/01-introduction.ts
// ============================================
// 01. Introduction to TypeScript
// ============================================
// Example 1: Basic TypeScript vs JavaScript
function add(a: number, b: number): number {
return a + b;
}
// This will cause a compile-time error:
// add(5, "10"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'
// Correct usage:
console.log(add(5, 10)); // 15
// Example 2: Type Inference
let count = 42; // TypeScript infers: number
let name = "Alice"; // TypeScript infers: string
let isActive = true; // TypeScript infers: boolean
console.log(`Count: ${count}, Name: ${name}, Active: ${isActive}`);
// Example 3: Type Annotations
let age: number = 25;
let username: string = "alice";
let isStudent: boolean = true;
console.log(`Age: ${age}, Username: ${username}, Student: ${isStudent}`);
// Example 4: Your First TypeScript Program
function greet(name: string): string {
return `Hello, ${name}!`;
}
const message = greet("TypeScript");
console.log(message); // "Hello, TypeScript!"
// Example 5: Type Safety Benefits
function calculateArea(width: number, height: number): number {
return width * height;
}
// TypeScript catches errors at compile time:
// calculateArea("5", 10); // Error!
// calculateArea(5, 10); // OK: 50
export { add, greet, calculateArea };
相关文章
02-basic-types.ts
02-basic-types.ts — typescript source code from the Typescript learning materials (Typescript/src/01-beginner/02-basic-types.ts).
阅读文章 →03-variables.ts
03-variables.ts — typescript source code from the Typescript learning materials (Typescript/src/01-beginner/03-variables.ts).
阅读文章 →04-functions.ts
04-functions.ts — typescript source code from the Typescript learning materials (Typescript/src/01-beginner/04-functions.ts).
阅读文章 →05-interfaces.ts
05-interfaces.ts — typescript source code from the Typescript learning materials (Typescript/src/01-beginner/05-interfaces.ts).
阅读文章 →06-classes.ts
06-classes.ts — typescript source code from the Typescript learning materials (Typescript/src/01-beginner/06-classes.ts).
阅读文章 →07-arrays-tuples.ts
07-arrays-tuples.ts — typescript source code from the Typescript learning materials (Typescript/src/01-beginner/07-arrays-tuples.ts).
阅读文章 →