TypeScript Features
\n\nCompared to JavaScript, TypeScript adds many key features, particularly around type system and code structure enhancements.
\n\nSome key features of TypeScript:
\n\n- \n
- Static Type Checking: TypeScript checks whether types in code match at compile time, and can discover many potential errors. Even simple errors (such as typos or type mismatches) can be caught while writing code. \n\n
- Type Inference: TypeScript can automatically infer the type of variables. For example, when you declare a variable and assign a value, TypeScript will infer the variable's type based on the assignment, without needing to explicitly declare the type every time. \n\n
- Interfaces and Type Definitions: TypeScript provides
interfaceandtypekeywords, allowing you to define complex data structures. This is very important for collaboration and data interaction between different parts of a project. \n\n - Class and Module Support: TypeScript supports the class concept in object-oriented programming, adding constructors, inheritance, access control modifiers (such as
public,private,protected), and supports ES module specifications. \n\n - Tool and Editor Support: TypeScript has excellent editor support, especially when integrated with Visual Studio Code, providing intelligent hints, auto-completion, refactoring and other tools to make the development process more efficient. \n\n
- JavaScript Compatibility: TypeScript is a superset of JavaScript, which means all valid JavaScript code is valid TypeScript code. This allows JavaScript projects to gradually migrate to TypeScript without complete rewriting. \n
Here are the main features TypeScript adds:
\n\n1. Static Types
\n\nTypeScript's biggest feature is the addition of a static type system. In TypeScript, developers can explicitly declare types for variables, parameters, and return values, which can catch many potential type errors at compile time. Common types include number, string, boolean, array, tuple, enum, etc., and custom types are also supported.
let name: string = "Alice";let age: number = 25;\n\n2. Type Inference
\n\nTypeScript can automatically infer variable types. Even without explicitly declaring types, TypeScript will infer the type based on the variable's assignment content, thus reducing the amount of type annotation writing in most cases.
\n\nlet name = "Alice"; // inferred as string\n\n3. Interfaces (Interfaces)
\n\nTypeScript provides interfaces, allowing complex object structures to be defined. Interfaces can define properties and methods, and can also implement interfaces with the implements keyword, or extend them with extends, making it easy to define complex data types.
interface Person { name: string; age: number; greet(): void;}class Student implements Person { constructor(public name: string, public age: number) {} greet() { console.log(`Hello, my name is ${this.name}`); }}\n\n4. Type Aliases (Type Aliases)
\n\nType aliases (type) can define short aliases for complex types, facilitating code reuse.
type StringOrNumber = string | number;let value: StringOrNumber = 42;\n\n5. Enums (Enums)
\n\nTypeScript introduces the enum type, used to define a set of named constants, improving code readability. Enums have no direct counterpart in JavaScript.
enum Direction { Up, Down, Left, Right,}let dir: Direction = Direction.Up;\n\n6. Tuples (Tuples)
\n\nTuples allow defining arrays with fixed number and types of elements. They are suitable for scenarios requiring fixed data structures, such as coordinates or RGB color values.
\n\nlet point: [number, number] = [10, 20];\n\n7. Access Modifiers (Access Modifiers)
\n\nTypeScript provides public, private, and protected modifiers in classes, allowing control over the visibility of properties or methods, supporting better encapsulation.
class Person { private name: string; protected age: number; public constructor(name: string, age: number) { this.name = name; this.age = age; }}\n\n8. Abstract Classes (Abstract Classes)
\n\nTypeScript supports abstract classes, which cannot be directly instantiated and need to be implemented by subclasses. Abstract classes are suitable for defining class hierarchies with common behavior and abstract methods.
\n\nabstract class Animal { abstract makeSound(): void;}class Dog extends Animal { makeSound() { console.log("Woof!"); }}\n\n9. Generics (Generics)
\n\nTypeScript supports generics, allowing parameterized types to be used in classes, interfaces, and functions, enabling code to adapt to different type requirements while maintaining type safety.
\n\nfunction identity<T>(value: T): T { return value;}let num = identity<number>(42);\n\n10. Modules and Namespaces
\n\nTypeScript provides an ES6-based module system, using import and export to import and export modules. Additionally, TypeScript supports namespaces (Namespace) for organizing code and avoiding naming conflicts.
// math.tsexport function add(a: number, b: number): number { return a + b;}// main.tsimport { add } from "./math"; console.log(add(2, 3));\n\n11. Type Guards (Type Guards)
\n\nTypeScript provides type guards, which can check variable types in code, helping the compiler infer more specific types. This is particularly important for union types.
\n\nfunction printId(id: string | number) { if (typeof id === "string") { console.log(id.toUpperCase()); } else { console.log(id.toFixed(2)); }}\n\n12. Optional Chaining and Nullish Coalescing Operators
\n\nTypeScript adds JavaScript's optional chaining (?.) and nullish coalescing operator (??), simplifying the handling of values that may be null or undefined in code.
let user = { name: "Alice", address: { city: "Wonderland" } }; console.log(user?.address?.city); // if address exists, output city, otherwise return undefinedlet value = null; console.log(value ?? "default"); // if value is null or undefined, return "default"\n\n13. Type Compatibility and Utility Types
\n\nTypeScript provides some utility types, such as Partial, Pick, Readonly, Record, etc. These types can help generate new types, simplifying type definitions.
interface Todo { title: string; description: string;}let partialTodo: Partial<Todo> = { title: "Learn TypeScript" }; // optional properties\n\n14. Compile-time Error Checking
\n\nTypeScript's compile-time error checking can catch errors that are not easily found in JavaScript, such as typos, type mismatches, etc., helping to improve code quality.
\n\n15. ES New Features Support
\n\nTypeScriptahead of timesupport(aspect particle indicating completed action or change of state)some not yet in all environments widely adopted (possessive particle) ES featuresοΌsuch asDecoratorsοΌDecoratorsοΌγasynchronousiteratorsetc. / and so onοΌandcanthemcompile tocompatible JavaScript versionsγ
\n\nThrough these features, TypeScript provides safer and more structured code capabilities, especially advantageous in large projects and multi-person collaboration.
YouTip