github:https://github.com/Jessie-jzn
网站:https://www.jessieontheroad.com/
1。静态类型检查
TypeScript 的核心优势是它的静态类型检查,这有助于在编译阶段而不是运行时捕获常见错误。这增强了代码的可靠性和稳定性。
2。增强的代码编辑体验
TypeScript 的类型系统可以在编辑器中实现更准确的代码补全、重构、导航和文档功能,显着提高开发效率。
3。提高代码可维护性
类型声明使理解代码意图和结构变得更容易,这在团队开发环境中特别有益。
4。高级语言功能
TypeScript 支持 JavaScript 中不存在的高级功能,例如接口、枚举和泛型,有助于开发更加结构化和可扩展的代码。
5。更好的工具支持
TypeScript 提供各种编译器选项来优化生成的 JavaScript 代码,并通过将 TypeScript 编译为兼容的 JavaScript 来支持不同的 JS 环境。
TypeScript | JavaScript | |
---|---|---|
Type System | Static typing with compile-time type checks. Types can be specified for variables, function parameters, and return values. | Dynamic typing with runtime type checks, which can lead to type-related runtime errors. |
Type Annotations | Supports type annotations to explicitly define types. E.g., let name: string = "Alice"; | No type annotations. Types are determined at runtime. |
Compilation | Requires compilation to JavaScript. TypeScript compiler checks for type errors and generates equivalent JavaScript code. | Runs directly in browsers or Node.js without a compilation step. |
Object-Oriented Programming | Richer OOP features such as classes, interfaces, abstract classes, and access modifiers. | Basic OOP features with prototype-based inheritance. |
Advanced Features | Includes all ES6 and ES7 features, plus additional features like generics, enums, and decorators. | Supports ES6 and later standards, but lacks some of the advanced features provided by TypeScript. |
Les génériques permettent aux fonctions, classes et interfaces de fonctionner avec n'importe quel type tout en garantissant la sécurité des types.
Exemple :
function identity<T>(arg: T): T { return arg; } const numberIdentity = identity<number>(42); const stringIdentity = identity<string>("Hello");
Dans cet exemple, la fonction d'identité utilise un
let anyVar: any; let unknownVar: unknown; anyVar = 5; anyVar.toUpperCase(); // No compile-time error, but might cause runtime error unknownVar = "Hello"; if (typeof unknownVar === "string") { unknownVar.toUpperCase(); // Type check ensures safety }
const obj = { name: "John" }; obj.name = "Doe"; // Allowed interface User { readonly id: number; name: string; } const user: User = { id: 1, name: "John" }; user.name = "Doe"; // Allowed user.id = 2; // Error, `id` is readonly
Les décorateurs sont une fonctionnalité TypeScript spéciale qui permet d'ajouter des métadonnées ou de modifier des classes, des méthodes, des propriétés ou des paramètres.
Types :
Exemples :
function sealed(constructor: Function) { Object.seal(constructor); Object.seal(constructor.prototype); } @sealed class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return `Hello, ${this.greeting}`; } }
function logMethod(target: any, propertyName: string, descriptor: PropertyDescriptor) { const originalMethod = descriptor.value; descriptor.value = function (...args: any[]) { console.log(`Method ${propertyName} called with args: ${JSON.stringify(args)}`); return originalMethod.apply(this, args); }; } class Calculator { @logMethod add(a: number, b: number): number { return a + b; } }
Utilisation :
Les décorateurs sont activés en définissant experimentalDecorators sur true dans tsconfig.json.
interface et type sont tous deux utilisés pour définir des types d'objets, mais ils présentent quelques différences :
interface | type | |
---|---|---|
Basic Usage | Defines the shape of objects, including properties and methods. | Defines primitive types, object types, union types, intersection types, etc. |
Extension | Supports declaration merging. Multiple declarations of the same interface are automatically merged. | Does not support declaration merging. |
Union and Intersection Types | Not supported. | Supports union (` |
Primitive Type Aliases | Not supported. | Supports aliasing primitive types. |
Mapped Types | Not supported. | Supports mapped types. |
Class Implementation | Supports class implementation using implements. | Does not support direct class implementation. |
tapez
以上是【面试精要】常见TypeScript面试题的详细内容。更多信息请关注PHP中文网其他相关文章!