YouTip LogoYouTip

Ts Intro

TypeScript is a programming language developed and open-sourced by Microsoft. It is a superset of JavaScript that, while fully compatible with JavaScript syntax, adds an optional static type system and class-based object-oriented programming capabilities. TypeScript code is ultimately compiled into pure JavaScript and can run in any environment that supports JavaScript, including browsers, Node.js, and mobile devices. !(#) * * * ## Why TypeScript is Needed JavaScript is a dynamically typed language, where variable types are determined at runtime. This flexibility works well in small projects, but as project scale grows, problems gradually emerge: | Problem Scenario | JavaScript's Dilemma | TypeScript's Solution | | --- | --- | --- | | Wrong type passed to function parameter | Error only at runtime, hard to detect early | Compile-time error, real-time IDE hints | | Accessing non-existent property | Returns `undefined`, behavior unpredictable | Compiler directly errors, won't pass | | Large project refactoring | Change one place, don't know what will break | Type system automatically tracks all references | | Team collaboration | What parameters functions accept, what they return all rely on comments or docs | Type signatures are documentation, IDE auto-completes | | Code readability | Looking at function definition can't directly know data structure | Interfaces and type aliases make data structure clear | > The essential goal of TypeScript is not to replace JavaScript, but to make large-scale JavaScript projects manageable and maintainable. It is JavaScript's "safety net," not a competitor. Let's look at the most intuitive example: ## Instance // JavaScript: Error only appears at runtime function greet(name){ return"Hello, "+ name.toUpperCase(); } greet(123);// Runtime error: name.toUpperCase is not a function ## Instance // TypeScript: Error can be detected at compile time function greet(name: string): string { return"Hello, "+ name.toUpperCase(); } greet(123);// Compile error: Argument of type 'number' is not assignable to parameter of type 'string' greet("tutorial");// Correct: Hello, TUTORIAL * * * ## Relationship Between TypeScript and JavaScript The relationship between TypeScript and JavaScript can be summarized in one sentence: TypeScript is a superset of JavaScript, meaning all valid JavaScript code is also valid TypeScript code. Set relationship diagram JavaScript (all JS code) βŠ‚ TypeScript (JS + type system + new features) βŠ‚ Compiled output (standard JavaScript, can run in any environment) Core differences comparison: | Comparison | JavaScript | TypeScript | | --- | --- | --- | | Type system | Dynamic, determined at runtime | Static, checked at compile time (optional) | | Execution | Runs directly in browser / Node.js | Must be compiled to JS first before running | | Error detection timing | Runtime | Compile time (early detection) | | IDE support | Basic completion | Strong type inference, precise completion, refactoring support | | Learning curve | Relatively gentle | Need to learn type system additionally | | Existing JS compatibility | β€” | Fully compatible, can migrate progressively | | File extension | `.js` | `.ts` or `.tsx` (with JSX) | > TypeScript supports "progressive adoption": you don't have to rewrite the entire project at once. You can first change `.js` to `.ts`, gradually add types to key modules, and existing code will continue to work. * * * ## Core Features TypeScript introduces a complete type system on top of JavaScript. Here are the most commonly used core features. ### Basic Type Annotations Declare types after variables, function parameters, and return values using a colon. This is the most basic syntax in TypeScript. ## Instance // Basic types: number, string, boolean, null, undefined, symbol, bigint let age: number =25; let username: string ="tutorial"; let isActive:boolean=true; // Array type, two equivalent notations let scores: number[]=[90,85,92]; let tags: Array=["typescript","javascript"]; // Tuple: array with fixed length and types let point:[number, number]=[10,20]; let entry:[string, number]=["TUTORIAL",100]; // Function: parameter types + return type function add(a: number, b: number): number { return a + b; } // void: function has no return value function log(msg: string):void{ console.log(msg); } // Optional parameter: add ? after parameter name function greet(name: string, title?: string): string { return title ? `${title} ${name}` : name; } console.log(greet("TUTORIAL"));// Output: TUTORIAL console.log(greet("tutorial","Mr."));// Output: Mr. tutorial ### Interface Interfaces are used to describe the "shape" of an object, defining what properties and methods an object should have. ## Instance // Define interface: describe the structure of a user object interface User { id: number;// Required name: string;// Required email?: string;// Optional, marked with ? readonly role: string;// Read-only, cannot be modified after assignment } // Use interface type for function parameter function printUser(user: User):void{ console.log(`ID: ${user.id}, Name: ${user.name}`); if(user.email){ console.log(`Email: ${user.email}`); } } const admin: User ={ id:1, name:"TUTORIAL", email:"tutorial@example.com", role:"admin", }; printUser(admin); // Output: ID: 1, Name: TUTORIAL // Output: Email: tutorial@example.com // admin.role = "user"; // Error: Cannot assign to 'role' because it is a read-only property. // Interface inheritance interface AdminUser extends User { permissions: string[]; } ### Type Alias Type aliases are created using the `type` keyword and can define aliases for any type, including union types, intersection types, and other complex structures. ## Instance // Union type: variable can be one of multiple types type ID = string | number; let userId: ID ="abc-123";// Valid userId =456;// Also valid // Literal type: restrict variable to specific values only type Direction ="up"|"down"|"left"|"right"; type Status ="pending"|"active"|"inactive"; function move(dir: Direction):void{ console.log(`Moving ${dir}`); } move("up");// Correct // move("diagonal"); // Error: not within literal range // Intersection type: merge multiple types type WithTimestamp ={ createdAt:Date; updatedAt:Date; }; type UserRecord = User & WithTimestamp;// Has all properties of both User and WithTimestamp // Function type alias type Transformer=(input: T)=> U; const toNumber: Transformer=(s)=> parseInt(s,10); ### Generics Generics allow writing reusable components while maintaining type safety. You can think of generics as "variables for types" β€” you pass in specific types when using them. ## Instance // Non-genericsyntax: can only handle number type function firstNumber(arr: number[]): number { return arr; } // Using generics: T is a type parameter, determined at call time function first(arr: T[]): T { return arr; } const n = first([1,2,3]);// n's type is number const s = first(["a","b"]
← Vue3 IntroductionPython2 Vscode Setup β†’