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

目录
相关文章
|
29天前
|
JavaScript 编译器
typescript之泛型
typescript之泛型
|
8天前
|
JavaScript
typeScript基础(1)_原始数据类型学习
本文介绍了TypeScript中的原始数据类型,包括布尔型、数值型、字符串型、`void`、`null`和`undefined`,并展示了如何在TypeScript中声明和使用这些类型。同时,还介绍了如何通过`tsc`命令编译TypeScript文件。
32 4
|
8天前
|
JavaScript 安全
typeScript进阶(14)_泛型和注意事项
TypeScript中的泛型允许创建可重用的代码。泛型可以定义函数、接口、类,支持传递类型参数,实现类型安全。泛型可以用于数组,约束类型参数必须符合特定的接口,也可以在接口和类中使用。泛型类可以包含多个类型参数,甚至在泛型约束中使用类型参数。
11 0
typeScript进阶(14)_泛型和注意事项
|
23天前
|
JavaScript
TypeScript 详解之 TypeScript 模块
TypeScript 详解之 TypeScript 模块
|
6天前
|
JavaScript 前端开发 编译器
TypeScript,从0到入门带你进入类型的世界
该文章提供了TypeScript的入门指南,从安装配置到基础语法,再到高级特性如泛型、接口等的使用,帮助初学者快速掌握TypeScript的基本用法。
|
2月前
|
JavaScript 安全 算法
TypeScript:一个好泛型的价值
TypeScript:一个好泛型的价值
|
2月前
|
JavaScript IDE 开发工具
|
2月前
|
开发框架 JSON 缓存
基于SqlSugar的开发框架循序渐进介绍(22)-- Vue3+TypeScript的前端工作流模块中实现统一的表单编辑和表单详情查看处理
基于SqlSugar的开发框架循序渐进介绍(22)-- Vue3+TypeScript的前端工作流模块中实现统一的表单编辑和表单详情查看处理
|
4月前
|
JavaScript 前端开发 IDE
TypeScript中的声明文件(.d.ts):扩展类型系统
TypeScript的`.d.ts`声明文件为JS库提供类型信息,增强IDE支持,如自动完成和类型检查。通过声明合并,可在全局作用域定义类型。示例包括为`my-library`创建声明模块,导出函数和接口。声明文件通常存于`@types`或指定`typeRoots`。用于旧JS代码的类型注解,如`myGlobalObject`。学习更多,参阅TypeScript官方文档。分享你的TS声明文件经验!
117 1
|
3月前
|
JavaScript 前端开发 安全
如何学习typescript?
【7月更文挑战第9天】1. 了解其为JavaScript超集,增加类型系统和ES6特性,提升代码安全性和效率。 2. 安装 TypeScript 全局 (`npm install -g typescript`),用`tsc -v`验证,或尝试在线的TypeScript Playground。 3. 学习类型注解、基础类型(如number、string、boolean等)、any与unknown,接口和类。 4. 探索高级特性,如泛型、模块&命名空间、装饰器。 5. 实践中巩固知识,如做小项目(如用React或Vue),阅读官方文档,参与社区讨论。持续编码和实践是关键。
24 0
下一篇
无影云桌面