TypeScript【泛型1、泛型2、声明合并、命名空间 、模块1、模块2、声明文件简介】(五)-全面详解(学习总结---从入门到深化)(上)

简介: TypeScript【泛型1、泛型2、声明合并、命名空间 、模块1、模块2、声明文件简介】(五)-全面详解(学习总结---从入门到深化)

泛型1



泛型(Generics)是指在定义函数、接口或类的时候,不预先指定具体的类型,而在使用的时候再指定类型的一种特性


首先,我们来实现一个函数 createArray

function createArray(length: number, value: any): Array<any> {
  let result = [];
  for (let i = 0; i < length; i++) {
    result[i] = value;
 }
  return result;
}
createArray(3, 'x'); // ['x', 'x', 'x']


这段代码编译不会报错,但是一个显而易见的缺陷是,它并没有准确的定义返回值的类型


Array 允许数组的每一项都为任意类型。但是我们预期的是,数组中每一项都应该是输入的 value 的类型


这时候,泛型就派上用场了

function createArray<T>(length: number, value: T): Array<T> {
  let result: T[] = [];
  for (let i = 0; i < length; i++) {
    result[i] = value;
 }
  return result;
}
createArray<string>(3, 'x'); // ['x', 'x','x']


泛型2



多个类型参数

function swap<T, U>(v1:T,v2:U) {
  console.log(v1,v2)
}
swap(10,20);


泛型约束


在函数内部使用泛型变量的时候,由于事先不知道它是哪种类型,所以不能随意的操作它的属性或方法

function loggingLength<T>(arg: T){
  // Property 'length' does not exist on type 'T'
  console.log(arg.length);
}


这时,我们可以对泛型进行约束,只允许这个函数传入那些包含 length 属性的变量。这就是泛型约束

interface Length {
  length: number;
}
function loggingIdentity<T extends Length> (arg: T){
  console.log(arg.length);
}
loggingIdentity("Hello")


声明合并



如果定义了两个相同名字的函数、接口或类,那么它们会合并成一个类型


函数的合并


我们可以使用重载定义多个函数类型

function reverse(x: number): number;
function reverse(x: string): string;
function reverse(x: number | string): number | string {
  if (typeof x === 'number') {
    return Number(x.toString().split('').reverse().join(''));
 } else if (typeof x === 'string') {
    return x.split('').reverse().join('');
 }
}


接口的合并


接口中的属性在合并时会简单的合并到一个接口中

interface Alarm {
  price: number;
}
interface Alarm {
  weight: number;
}


相当于:

interface Alarm {
  price: number;
  weight: number;
}


注意,合并的属性的类型必须是唯一的:

interface Alarm {
  price: number;
}
interface Alarm {
  price: number;  // 虽然重复了,但是类型都是 `number`,所以不会报错
  weight: number;
}
interface Alarm {
  price: number;
}
interface Alarm {
  price: string;  // 类型不一致,会报错
  weight: number;
}


命名空间



在真实的应用场景中,当在一个文件中代码量过多,不容易阅读和维护的时候,我们可以通过命名空间的方式将一个文件分离为多个文件


我们来观察下面这个例子:

interface Animal{
  name:string
}
class Cat implements Animal{
  name: string
  constructor(name:string){
    this.name = name;
 }
  sayHi(){
    console.log(this.name)
 }
}
class Dog implements Animal{
  name: string
  constructor(name:string){
    this.name = name
 }
  sayHello(){
    console.log(this.name)
 }
}
const c = new Cat("猫")
c.sayHi()
const d = new Dog("狗")
d.sayHello()


当应用变得越来越大时,我们需要将代码分离到不同的文件中以便于维护

// Animal.ts
namespace AnimalInfo{
  export interface Animal{
    name:string
 }
}
// Cat.ts
namespace AnimalInfo{
  export class Cat implements Animal{
    name: string
    constructor(name:string){
      this.name = name;
   }
    sayHi(){
      console.log(this.name)
   }
 }
}
// Dog.ts
namespace AnimalInfo{
  export class Dog implements Animal{
    name: string
    constructor(name:string){
      this.name = name
   }
    sayHello(){
      console.log(this.name)
   }
 }
}
// index.ts
const c = new AnimalInfo.Cat("猫")
c.sayHi()
const d = new AnimalInfo.Dog("狗")
d.sayHello()


TypeScript【泛型1、泛型2、声明合并、命名空间 、模块1、模块2、声明文件简介】(五)-全面详解(学习总结---从入门到深化)(下):https://developer.aliyun.com/article/1420374

目录
相关文章
|
14天前
|
JavaScript 前端开发 安全
TypeScript 终极入门指南:从零到精通 🚀
TypeScript是JavaScript的超集,添加静态类型系统,提升代码健壮性与可维护性。本教程涵盖基础类型、高级特性、面向对象编程及最佳实践,配代码示例与图解,助你快速掌握TS核心概念,轻松进阶前端开发!🎉
236 2
TypeScript 终极入门指南:从零到精通 🚀
|
3月前
|
安全 JavaScript 编译器
TypeScript 泛型:解锁灵活且安全的代码重用
TypeScript 泛型:解锁灵活且安全的代码重用
|
3月前
|
存储 JavaScript 安全
TypeScript 泛型:让你的代码既灵活又安全的“魔法”
TypeScript 泛型:让你的代码既灵活又安全的“魔法”
|
6月前
|
人工智能 JavaScript 程序员
一文彻底搞明白HarmonyOS基础TypeScript中的泛型函数
程序员Feri是一位拥有12年+经验的技术专家,擅长嵌入式、鸿蒙、人工智能和Java等领域。本文深入探讨TypeScript中的泛型函数,涵盖基础语法、类型约束、高级技巧及应用场景。通过泛型函数,实现代码逻辑与具体类型的解耦,提升类型安全性和复用性。内容包括集合操作、API抽象、工具类开发等实际应用,以及条件类型、默认类型参数和工具类型的高级技巧。最后提醒开发者注意过度泛型化和性能权衡问题,总结泛型函数在TypeScript类型系统中的核心地位及其未来发展方向。
114 1
一文彻底搞明白HarmonyOS基础TypeScript中的泛型函数
|
JavaScript 编译器
typescript之泛型
typescript之泛型
214 60
|
11月前
|
设计模式 JavaScript 安全
TypeScript性能优化及代码质量提升的重要性、方法与策略,包括合理使用类型注解、减少类型断言、优化模块导入导出、遵循编码规范、加强代码注释等
本文深入探讨了TypeScript性能优化及代码质量提升的重要性、方法与策略,包括合理使用类型注解、减少类型断言、优化模块导入导出、遵循编码规范、加强代码注释等,旨在帮助开发者在保证代码质量的同时,实现高效的性能优化,提升用户体验和项目稳定性。
257 6
|
JavaScript 安全
typeScript进阶(14)_泛型和注意事项
TypeScript中的泛型允许创建可重用的代码。泛型可以定义函数、接口、类,支持传递类型参数,实现类型安全。泛型可以用于数组,约束类型参数必须符合特定的接口,也可以在接口和类中使用。泛型类可以包含多个类型参数,甚至在泛型约束中使用类型参数。
132 1
typeScript进阶(14)_泛型和注意事项
|
12月前
|
JavaScript 前端开发
TypeScript【类型别名、泛型】超简洁教程!再也不用看臭又长的TypeScript文档了!
【10月更文挑战第11天】TypeScript【类型别名、泛型】超简洁教程!再也不用看臭又长的TypeScript文档了!
|
12月前
|
JavaScript 前端开发 编译器
【小白入门】 浏览器如何识别Typescript?
【10月更文挑战第1天】浏览器如何识别Typescript?
|
JavaScript
typeScript基础(1)_原始数据类型学习
本文介绍了TypeScript中的原始数据类型,包括布尔型、数值型、字符串型、`void`、`null`和`undefined`,并展示了如何在TypeScript中声明和使用这些类型。同时,还介绍了如何通过`tsc`命令编译TypeScript文件。
146 4