TS 是 TypeScript 的缩写,是一种由微软开发的开源编程语言,它是 JavaScript 的一个超集,为 JavaScript 添加了类型系统和对 ES6+ 的支持。以下是关于 TypeScript 的详细介绍:

一、特点

  • 类型系统:TypeScript 引入了类型注解,允许开发者为变量、函数参数、返回值等添加类型信息。这有助于在编译阶段发现潜在的类型错误,提高代码的健壮性和可维护性。例如:

    let message: string = "Hello, TypeScript!";
    function add(a: number, b: number): number {return a + b;
    }

    在 TypeScript 中,typeinterface 都可以用来定义复杂数据类型,它们各有特点和适用场景,以下是详细介绍:

二、使用 type 定义复杂数据类型

  • 基本语法
type TypeName = {property1: Type1;property2: Type2;// ...
};
  • 定义对象类型
type Person = {name: string;age: number;address: {street: string;city: string;};
};
  • 定义联合类型
    type StringOrNumber = string | number;
  • 定义交叉类型: 
    type Employee = {employeeId: number;
    } & Person;
  • 定义泛型类型: 
    type Container<T> = {value: T;
    };

    三、使用 interface 定义复杂数据类型

  • 基本语法: 
    interface InterfaceName {property1: Type1;property2: Type2;// ...
    }
  • 定义对象类型: 
    interface Person {name: string;age: number;address: {street: string;city: string;};
    }
  • 定义类类型: 
    interface Person {name: string;age: number;greet(): void;
    }
    class Student implements Person {name: string;age: number;constructor(name: string, age: number) {this.name = name;this.age = age;}greet() {console.log(`Hello, my name is ${this.name}`);}
    }

    type 与 interface 的区别与选择

  • 区别

    • type 是类型别名,可以为任何类型定义一个新的名字,包括基本类型、联合类型、交叉类型等;而 interface 主要用于定义对象类型或类类型。

    • interface 可以被类实现(implements),而 type 不行。

    • interface 可以继承其他接口,而 type 不行。

    • type 定义的类型可以使用交叉类型(&)来组合多个类型,而 interface 只能继承一个接口。

  • 选择

    • 如果需要定义一个对象类型或类类型,并且希望使用继承或类实现,建议使用 interface

    • 如果需要定义联合类型、交叉类型或泛型类型,或者需要为复杂类型定义别名,建议使用 type

    • 在实际开发中,可以根据具体需求和团队编码规范来选择使用 typeinterface

四、 函数类型

在 TypeScript 中,函数类型用于描述函数的参数类型和返回值类型。你可以通过类型别名(type)或接口(interface)来定义函数类型。 

interface Api {foo(): void;bar(str: string): string;
}function test(api: Api) {api.foo();const result = api.bar("hello");console.log(result);
}// 调用 test 函数
test({foo() {console.log('ok');},bar(str: string) {return str.toUpperCase();}
});

五、字面量与nullish类型

// 字面量类型:功能:输出一段文字(参数1),参数2决定文字的对齐方式
function printText(text: string, alignment: "left" | "right" | "center") {console.log(text, alignment);
}printText("Hello", "left");
printText("Hello", "center");// nullish 类型 null undefined
function test(x?: string | null) {// if (x !== null && x !== undefined)// console.log(x.toUpperCase());  // 错误:x 可能为 null 或 undefinedconsole.log(x?.toUpperCase());   // 正确:使用可选链
}test("hello");
test(null);
test();

六、泛型

interface Ref<T> {value: T;
}const r1: Ref<string> = { value: 'hello' };
const r2: Ref<number> = { value: 123 };
const r3: Ref<boolean> = { value: true };function test1(n: string) {return { value: n };
}function test2(n: number) {return { value: n };
}function ref<T>(n: T): Ref<T> {return { value: n };
}const v1 = ref("hello");      // Ref<string>
const v2 = ref(123.3333);     // Ref<number>
console.log(v2.value.toFixed(2));  // 输出: 123.33

 七、class语法

一个基本的类定义包括类名、属性(成员变量)和方法(成员函数):

class Person {// 类属性(成员变量)firstName: string;lastName: string;// 构造函数constructor(firstName: string, lastName: string) {this.firstName = firstName;this.lastName = lastName;}// 类方法(成员函数)fullName(): string {return `${this.firstName} ${this.lastName}`;}
}

继承

TypeScript 支持类的继承,可以使用 extends 关键字来实现:

class Employee extends Person {employeeId: number;constructor(firstName: string, lastName: string, employeeId: number) {super(firstName, lastName);  // 调用父类的构造函数this.employeeId = employeeId;}work(): string {return `${this.fullName()} is working`;}
}

访问修饰符

TypeScript 提供了三种访问修饰符:

  • public:公共的,可以在任何地方访问。

  • private:私有的,只能在类内部访问。

  • protected:受保护的,可以在类内部和子类中访问。

    class Person {private name: string;constructor(name: string) {this.name = name;}public getName(): string {return this.name;}
    }

    抽象类

    抽象类是不能被实例化的类,通常用作基类:

    abstract class Animal {abstract makeSound(): void;move(): void {console.log("Moving");}
    }class Dog extends Animal {makeSound(): void {console.log("Bark");}
    }

    静态成员

    类可以包含静态属性和方法,这些成员属于类本身,而不是类的实例:

    class Utils {static pi: number = 3.14;static calculateCircleArea(radius: number): number {return Utils.pi * radius * radius;}
    }

    类表达式

    类也可以作为表达式定义,这在定义匿名类时非常有用:

    const Animal = class {makeSound() {console.log("Some generic sound");}
    };const dog = new Animal();
    dog.makeSound();  // 输出: Some generic sound

    类类型

    类本身可以作为类型使用:

    let person: Person;
    person = new Person("Alice", "Smith");

    类与接口

    类可以实现接口,接口定义了类必须遵循的结构:

    interface Greeting {greet(): string;
    }class Hello implements Greeting {greet(): string {return "Hello";}
    }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/web/88958.shtml
繁体地址,请注明出处:http://hk.pswp.cn/web/88958.shtml
英文地址,请注明出处:http://en.pswp.cn/web/88958.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Excel快捷键

Excel快捷键可以快速提高使用Excel的效率&#xff0c;下面将Excel快捷键进行整理汇总以备不时之需 标注颜色的为需要经常使用并可以显著提高效率的快捷键 Ctrl相关快捷键【Ctrl】【1】 显示【单元格格式】设置窗口,可以设置选中的格式【Ctrl】【2】 应用或取消加粗…

Windows 10/11安装WSL、Ubuntu、Docker Desktop

WSL&#xff0c;Windows Subsystem for Linux&#xff0c;是微软开发的轻量级虚拟机环境&#xff0c;允许用户在 Windows上运行完整的Linux内核和用户空间&#xff0c;适用于Windows的Linux子系统。能实现&#xff1a; 运行原生的Linux命令和程序&#xff08;如apt&#xff0c…

React之旅-06 Ref

当你想让一个组件“记住”一些信息&#xff0c;但又不想这些信息触发新的渲染时&#xff0c;你可以使用 ref。使用 Ref 前&#xff0c;需要导入useRef&#xff0c;代码如下&#xff1a;import { useRef } from react;在您的组件内部&#xff0c;调用 useRef 并将您想要引用的初…

stm32-Modbus主机移植程序理解以及实战

目录一、背景二、代码理解&#xff08;一&#xff09;main()函数例程代码功能遇到的问题解决方式分析&#xff08;二&#xff09;eMBMasterPoll( void )函数例程代码1. 变量声明2. 协议栈状态检查3. 获取事件4. 事件处理&#xff08;switch-case&#xff09;4.1 EV_MASTER_READ…

c++判断文件或目录是否存在

#include<sys/stat.h>#include<fstream>#include<string>#include<stdio.h>#include<stdlib.h>#include<vector>#include<io.h>#include<iostream>bool IsFileGood(string strFileName, book bFile){if(bFile) \\文件{ifstrea…

Java设计模式之行为型模式(命令模式)

一、核心定义与设计思想 命令模式通过对象化请求&#xff0c;将操作的具体实现细节封装在命令对象中&#xff0c;使得调用者&#xff08;Invoker&#xff09;无需直接依赖接收者&#xff08;Receiver&#xff09;&#xff0c;仅需通过命令对象间接调用。这种设计支持以下能力&a…

大数据领域开山鼻祖组件Hadoop核心架构设计

一、Hadoop的整体架构 Hadoop是一个专为大数据设计的架构解决方案&#xff0c;历经多年开发演进&#xff0c;已逐渐发展成为一个庞大且复杂的系统。其内部工作机制融合了分布式理论与具体工程开发的精髓&#xff0c;构成了一个整体架构。 Hadoop最朴素的原理在于&#xff0c;它…

OneCode3.0 VFS分布式文件管理API速查手册

&#x1f4da; 前言&#xff1a;OneCode 3.0微内核引擎架构解析 在云原生与分布式系统日益普及的今天&#xff0c;文件管理系统面临着前所未有的挑战——海量数据存储、跨节点协同、多租户隔离以及弹性扩展等需求推动着传统文件系统向分布式架构演进。OneCode 3.0作为新一代企业…

UI前端与数字孪生结合实践探索:智慧物流的仓储自动化管理系统

hello宝子们...我们是艾斯视觉擅长ui设计、前端开发、数字孪生、大数据、三维建模、三维动画10年经验!希望我的分享能帮助到您!如需帮助可以评论关注私信我们一起探讨!致敬感谢感恩!一、引言&#xff1a;传统仓储的 “效率黑洞” 与数字孪生的破局当仓库管理员在数万平的库房中…

使用layui的前端框架过程中,无法加载css和js怎么办?

这使用layui的前端框架过程中&#xff0c;无法加载css和js怎么办&#xff1f;里写自定义目录标题已经按要求下载并解压到指定位置了&#xff0c;但是感觉就是无法加载文件后台提示如下&#xff1a;那就我清理缓存当再次观察html页面时&#xff0c;发现页面最开始有两个< htm…

gitlab+TortoiseGit克隆生成ppk方式

1、第一步 2、第二步3、第三步4、第四步&#xff0c;如何使用这个ppk就可以了

VSCode中使用容器及容器编排docker-compose

前面笔者写了一篇博文&#xff1a;使用容器编排对go项目进行部署、调试&#xff0c;介绍了在Goland中如何使用容器&#xff0c;由于Goland的容器配置是可视化的&#xff0c;使用起来非常方便&#xff0c;VSCode中也有一个容器插件&#xff0c;但是笔者一直未使用过&#xff0c;…

深度学习入门:让神经网络变得“深不可测“⚡(二)

深度学习入门&#xff1a;让神经网络变得"深不可测" &#x1f9e0;⚡ 系列课程第二弹&#xff1a;深度学习的奇妙世界 前言&#xff1a;从浅到深的华丽转身 哈喽&#xff0c;各位AI探险家&#xff01;&#x1f44b; 欢迎回到我们的"让机器变聪明"系列课…

硅基计划2.0 学习总结 捌 异常与常用工具类

文章目录一、异常1. 防御性编程2. throw关键字3. throws关键字4. 捕获5. finally关键字二、自定义异常类三、常用工具类1. Date以及相关的类1. 创建时间&#xff08;基本弃用&#xff09;2. 捕获系统时间3. 获取当前年月日时分秒4. 日期加减5. 根据字符串创建日期6. 根据当前时…

2025-7-14-C++ 学习 排序(2)

文章目录2025-7-14-C 学习 排序&#xff08;2&#xff09;P1059 [NOIP 2006 普及组] 明明的随机数题目描述输入格式输出格式输入输出样例 #1输入 #1输出 #1说明/提示提交代码P1093 [NOIP 2007 普及组] 奖学金题目背景题目描述输入格式输出格式输入输出样例 #1输入 #1输出 #1输入…

微信131~140

1.在组件中使用store对象的数据 // 要想使用store中的数据以及方法 // 需要从 mobx-miniprogram-bindings 方法将 ComponentWithStore 方法 import { ComponentWithStore } from mobx-miniprogram-bindings // 导入store对象 import { numStore } from ../../../stores/numstor…

微美全息借区块链与DRL算法打造资源管理协同架构,达成边缘计算与区块链动态适配

在当今数字化浪潮汹涌的时代&#xff0c;边缘计算与区块链技术正逐步成为驱动技术革新与业务转型升级的核心动力。当这两项前沿技术相互融合&#xff0c;一个兼具高效性与安全性的任务处理系统便得以构建。为了充分挖掘边缘计算系统的性能潜力&#xff0c;避免任务卸载过程中的…

属性绑定

简写模式二.为什么要这样做布尔型attribute动态绑定多个值

链表算法之【获取链表开始入环的节点】

目录 LeetCode-142题 LeetCode-142题 给定一个链表的头节点head&#xff0c;返回链表开始入环的第一个节点&#xff0c;如果链表无环&#xff0c;则返回null class Solution {public ListNode detectCycle(ListNode head) {// checkif (head null || head.next null)retur…

【网络编程】KCP——可靠的 UDP 传输协议——的知识汇总

文章目录前言UDP 协议UDP 的关键指标/特性UDP 的典型应用场景KCP 协议的基础KCP 的构造KCP 协议特性KCP 的可靠传输机制——ARQ三种 ARQ 机制对比KCP 的选择性重传一、基础机制&#xff1a;选择性重传&#xff08;SR&#xff09;二、KCP 对 SR 的增强策略KCP 的激进重传策略——…