TypeScript 是一种现代编程语言,由于其附加的类型安全性,通常比 JavaScript 更受青睐。在本文中,我将分享 10 个最重要的 TypeScript 概念,这将有助于提高您的 TypeScript 编程技能。准备好了吗?开始吧。
1.泛型:使用泛型我们可以创建可重用的类型,这将有助于处理今天和明天的数据。
泛型示例:
我们可能想要 Typescript 中的一个函数将参数作为某种类型,并且我们可能想要返回相同的类型。
function func<t>(args:T):T{ return args; } </t>
2.具有类型约束的泛型:现在让我们通过定义它只接受字符串和整数来限制类型 T:
function func<t extends string number>(value: T): T { return value; } const stringValue = func("Hello"); // Works, T is string const numberValue = func(42); // Works, T is number // const booleanValue = func(true); // Error: Type 'boolean' is not assignable to type 'string | number' </t>
3.通用接口:
当您想要为使用各种类型的对象、类或函数定义契约(形状)时,接口泛型非常有用。它们允许您定义一个蓝图,该蓝图可以适应不同的数据类型,同时保持结构一致。
// Generic interface with type parameters T and U interface Repository<t u> { items: T[]; // Array of items of type T add(item: T): void; // Function to add an item of type T getById(id: U): T | undefined; // Function to get an item by ID of type U } // Implementing the Repository interface for a User entity interface User { id: number; name: string; } class UserRepository implements Repository<user number> { items: User[] = []; add(item: User): void { this.items.push(item); } getById(idOrName: number | string): User | undefined { if (typeof idOrName === 'string') { // Search by name if idOrName is a string console.log('Searching by name:', idOrName); return this.items.find(user => user.name === idOrName); } else if (typeof idOrName === 'number') { // Search by id if idOrName is a number console.log('Searching by id:', idOrName); return this.items.find(user => user.id === idOrName); } return undefined; // Return undefined if no match found } } // Usage const userRepo = new UserRepository(); userRepo.add({ id: 1, name: "Alice" }); userRepo.add({ id: 2, name: "Bob" }); const user1 = userRepo.getById(1); const user2 = userRepo.getById("Bob"); console.log(user1); // Output: { id: 1, name: "Alice" } console.log(user2); // Output: { id: 2, name: "Bob" } </user></t>
4.泛型类::当您希望类中的所有属性都遵循泛型参数指定的类型时,请使用此选项。这允许灵活性,同时确保类的每个属性都与传递给类的类型匹配。
interface User { id: number; name: string; age: number; } class UserDetails<t extends user> { id: T['id']; name: T['name']; age: T['age']; constructor(user: T) { this.id = user.id; this.name = user.name; this.age = user.age; } // Method to get user details getUserDetails(): string { return `User: ${this.name}, ID: ${this.id}, Age: ${this.age}`; } // Method to update user name updateName(newName: string): void { this.name = newName; } // Method to update user age updateAge(newAge: number): void { this.age = newAge; } } // Using the UserDetails class with a User type const user: User = { id: 1, name: "Alice", age: 30 }; const userDetails = new UserDetails(user); console.log(userDetails.getUserDetails()); // Output: "User: Alice, ID: 1, Age: 30" // Updating user details userDetails.updateName("Bob"); userDetails.updateAge(35); console.log(userDetails.getUserDetails()); // Output: "User: Bob, ID: 1, Age: 35" console.log(new UserDetails("30")); // Error: "This will throw error" </t>
5.将类型参数约束为传递的类型:有时,我们希望参数类型依赖于其他一些传递的参数。听起来很混乱,让我们看下面的示例。
function getProperty<type>(obj: Type, key: keyof Type) { return obj[key]; } let x = { a: 1, b: 2, c: 3 }; getProperty(x, "a"); // Valid getProperty(x, "d"); // Error: Argument of type '"d"' is not assignable to parameter of type '"a" | "b" | "c"'. </type>
6.条件类型:通常,我们希望我们的类型是一种类型或另一种类型。在这种情况下,我们使用条件类型。
一个简单的例子是:
function func(param:number|boolean){ return param; } console.log(func(2)) //Output: 2 will be printed console.log(func("True")) //Error: boolean cannot be passed as argument
有点复杂的例子:
type HasProperty<t k extends keyof t> = K extends "age" ? "Has Age" : "Has Name"; interface User { name: string; age: number; } let test1: HasProperty<user>; // "Has Age" let test2: HasProperty<user>; // "Has Name" let test3: HasProperty<user>; // Error: Type '"email"' is not assignable to parameter of type '"age" | "name"'. </user></user></user></t>
6.交集类型:当我们想要将多种类型合并为一个类型时,这些类型非常有用,允许特定类型继承各种其他类型的属性和行为。
让我们看一个有趣的例子:
// Defining the types for each area of well-being interface MentalWellness { mindfulnessPractice: boolean; stressLevel: number; // Scale of 1 to 10 } interface PhysicalWellness { exerciseFrequency: string; // e.g., "daily", "weekly" sleepDuration: number; // in hours } interface Productivity { tasksCompleted: number; focusLevel: number; // Scale of 1 to 10 } // Combining all three areas into a single type using intersection types type HealthyBody = MentalWellness & PhysicalWellness & Productivity; // Example of a person with a balanced healthy body const person: HealthyBody = { mindfulnessPractice: true, stressLevel: 4, exerciseFrequency: "daily", sleepDuration: 7, tasksCompleted: 15, focusLevel: 8 }; // Displaying the information console.log(person);
7.infer 关键字:当我们想要有条件地确定特定类型时,infer 关键字很有用,并且当满足条件时,它允许我们从该类型中提取子类型。
这是一般语法:
type ConditionalType<t> = T extends SomeType ? InferredType : OtherType; </t>
示例:
type ReturnTypeOfPromise<t> = T extends Promise<infer u> ? U : number; type Result = ReturnTypeOfPromise<promise>>; // Result is 'string' type ErrorResult = ReturnTypeOfPromise<number>; // ErrorResult is 'never' const result: Result = "Hello"; console.log(typeof result); // Output: 'string' </number></promise></infer></t>
8.Type Variance:这个概念讨论了子类型和父类型如何相互关联。
它们有两种类型:
协方差:可以在需要父类型的地方使用子类型。
让我们看一个例子:
function func<t>(args:T):T{ return args; } </t>
在上面的示例中,Car 继承了 Vehicle 类的属性,因此将其分配给需要超类型的子类型是绝对有效的,因为子类型将具有超类型所具有的所有属性。
逆变:这与协变相反。我们在子类型应该出现的地方使用超类型。
function func<t extends string number>(value: T): T { return value; } const stringValue = func("Hello"); // Works, T is string const numberValue = func(42); // Works, T is number // const booleanValue = func(true); // Error: Type 'boolean' is not assignable to type 'string | number' </t>
使用逆变时,我们需要小心不要访问特定于子类型的属性或方法,因为这可能会导致错误。
9。反思: 这个概念涉及在运行时确定变量的类型。虽然 TypeScript 主要关注编译时的类型检查,但我们仍然可以利用 TypeScript 运算符在运行时检查类型。
typeof 运算符:我们可以利用 typeof 运算符在运行时查找变量的类型
// Generic interface with type parameters T and U interface Repository<t u> { items: T[]; // Array of items of type T add(item: T): void; // Function to add an item of type T getById(id: U): T | undefined; // Function to get an item by ID of type U } // Implementing the Repository interface for a User entity interface User { id: number; name: string; } class UserRepository implements Repository<user number> { items: User[] = []; add(item: User): void { this.items.push(item); } getById(idOrName: number | string): User | undefined { if (typeof idOrName === 'string') { // Search by name if idOrName is a string console.log('Searching by name:', idOrName); return this.items.find(user => user.name === idOrName); } else if (typeof idOrName === 'number') { // Search by id if idOrName is a number console.log('Searching by id:', idOrName); return this.items.find(user => user.id === idOrName); } return undefined; // Return undefined if no match found } } // Usage const userRepo = new UserRepository(); userRepo.add({ id: 1, name: "Alice" }); userRepo.add({ id: 2, name: "Bob" }); const user1 = userRepo.getById(1); const user2 = userRepo.getById("Bob"); console.log(user1); // Output: { id: 1, name: "Alice" } console.log(user2); // Output: { id: 2, name: "Bob" } </user></t>
instanceof 运算符:instanceof 运算符可用于检查对象是否是类或特定类型的实例。
interface User { id: number; name: string; age: number; } class UserDetails<t extends user> { id: T['id']; name: T['name']; age: T['age']; constructor(user: T) { this.id = user.id; this.name = user.name; this.age = user.age; } // Method to get user details getUserDetails(): string { return `User: ${this.name}, ID: ${this.id}, Age: ${this.age}`; } // Method to update user name updateName(newName: string): void { this.name = newName; } // Method to update user age updateAge(newAge: number): void { this.age = newAge; } } // Using the UserDetails class with a User type const user: User = { id: 1, name: "Alice", age: 30 }; const userDetails = new UserDetails(user); console.log(userDetails.getUserDetails()); // Output: "User: Alice, ID: 1, Age: 30" // Updating user details userDetails.updateName("Bob"); userDetails.updateAge(35); console.log(userDetails.getUserDetails()); // Output: "User: Bob, ID: 1, Age: 35" console.log(new UserDetails("30")); // Error: "This will throw error" </t>
我们可以使用第三方库在运行时确定类型。
10.依赖注入:依赖注入是一种模式,允许您将代码引入组件中,而无需在组件中实际创建或管理它。虽然它看起来像是使用库,但它有所不同,因为您不需要通过 CDN 或 API 安装或导入它。
乍一看,它似乎也类似于使用函数来实现可重用性,因为两者都允许代码重用。然而,如果我们直接在组件中使用函数,可能会导致它们之间的紧密耦合。这意味着函数或其逻辑的任何变化都可能影响它使用的每个地方。
依赖注入通过将依赖项的创建与使用它们的组件解耦来解决这个问题,使代码更易于维护和测试。
没有依赖注入的示例
function getProperty<type>(obj: Type, key: keyof Type) { return obj[key]; } let x = { a: 1, b: 2, c: 3 }; getProperty(x, "a"); // Valid getProperty(x, "d"); // Error: Argument of type '"d"' is not assignable to parameter of type '"a" | "b" | "c"'. </type>
依赖注入示例
function func(param:number|boolean){ return param; } console.log(func(2)) //Output: 2 will be printed console.log(func("True")) //Error: boolean cannot be passed as argument
在紧密耦合的场景中,如果您今天 MentalWellness 类中有一个stressLevel 属性,并决定明天将其更改为其他属性,则需要更新所有使用它的地方。这可能会导致许多重构和维护挑战。
但是,通过依赖注入和接口的使用,你可以避免这个问题。通过构造函数传递依赖项(例如 MentalWellness 服务),具体的实现细节(例如stressLevel 属性)被抽象到接口后面。这意味着只要接口保持不变,对属性或类的更改不需要修改依赖类。这种方法可确保代码松散耦合、更易于维护且更易于测试,因为您可以在运行时注入所需的内容,而无需紧密耦合组件。
以上是每个开发人员都应该了解的高级打字稿概念的详细内容。更多信息请关注PHP中文网其他相关文章!

JavaScript字符串替换方法详解及常见问题解答 本文将探讨两种在JavaScript中替换字符串字符的方法:在JavaScript代码内部替换和在网页HTML内部替换。 在JavaScript代码内部替换字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 该方法仅替换第一个匹配项。要替换所有匹配项,需使用正则表达式并添加全局标志g: str = str.replace(/fi

本教程向您展示了如何将自定义的Google搜索API集成到您的博客或网站中,提供了比标准WordPress主题搜索功能更精致的搜索体验。 令人惊讶的是简单!您将能够将搜索限制为Y

本文系列在2017年中期进行了最新信息和新示例。 在此JSON示例中,我们将研究如何使用JSON格式将简单值存储在文件中。 使用键值对符号,我们可以存储任何类型的

增强您的代码演示:开发人员的10个语法荧光笔 在您的网站或博客上共享代码片段是开发人员的常见实践。 选择合适的语法荧光笔可以显着提高可读性和视觉吸引力。 t

因此,在这里,您准备好了解所有称为Ajax的东西。但是,到底是什么? AJAX一词是指用于创建动态,交互式Web内容的一系列宽松的技术。 Ajax一词,最初由Jesse J创造

利用轻松的网页布局:8个基本插件 jQuery大大简化了网页布局。 本文重点介绍了简化该过程的八个功能强大的JQuery插件,对于手动网站创建特别有用

本文介绍了关于JavaScript和JQuery模型视图控制器(MVC)框架的10多个教程的精选选择,非常适合在新的一年中提高您的网络开发技能。 这些教程涵盖了来自Foundatio的一系列主题

核心要点 JavaScript 中的 this 通常指代“拥有”该方法的对象,但具体取决于函数的调用方式。 没有当前对象时,this 指代全局对象。在 Web 浏览器中,它由 window 表示。 调用函数时,this 保持全局对象;但调用对象构造函数或其任何方法时,this 指代对象的实例。 可以使用 call()、apply() 和 bind() 等方法更改 this 的上下文。这些方法使用给定的 this 值和参数调用函数。 JavaScript 是一门优秀的编程语言。几年前,这句话可


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

SublimeText3 Linux新版
SublimeText3 Linux最新版

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

WebStorm Mac版
好用的JavaScript开发工具

SublimeText3 英文版
推荐:为Win版本,支持代码提示!