TypeScript 常用特性
文章类型:TypeScript
发布者:hp
发布时间:2025-03-19
TypeScript 是 JavaScript 的超集,它为 JavaScript 添加了 静态类型检查 和更多现代语言特性,那么,常用的有那些呢?
1、静态类型检查:可以在编译时捕获类型错误,帮助减少运行时错误。通过显式地声明变量、函数参数和返回值的类型
let count: number = 10;
function add(a: number, b: number): number {
return a + b;
}
2、接口:用于定义对象的结构和行为,规定了对象应该具备哪些属性和方法
interface User {
name: string;
age: number;
isActive: boolean;
}
function greet(user: User): string {
return `Hello, ${user.name}`;
}
const user: User = { name: 'Alice', age: 25, isActive: true };
console.log(greet(user)); // Hello, Alice
3、类型别名:允许我们为复杂的类型定义简洁的别名,尤其在处理联合类型或嵌套类型时非常有用
type ID = string | number;
let userId: ID = 123;
userId = "abc";
4、联合类型和交叉类型:
联合类型:允许变量可以是多种类型中的一种
交叉类型:组合多个类型为一个类型,要求变量满足所有类型的约束
// 联合类型
function printId(id: string | number): void {
console.log(`ID: ${id}`);
}
// 交叉类型
interface Person {
name: string;
}
interface Employee {
employeeId: number;
}
type EmployeePerson = Person & Employee;
const emp: EmployeePerson = { name: "Alice", employeeId: 101 };
5、泛型:允许我们编写可以适应多种类型的代码,尤其在定义函数、接口和类时非常有用,可以在不牺牲类型安全性的前提下,让代码更具复用性
function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("hello");
let output2 = identity<number>(42);
6、类型推断:拥有强大的类型推断能力,能够根据变量的初始值自动推断其类型
let message = "Hello, World!"; // TypeScript 自动推断为 string 类型
7、类型守卫:用于在运行时检查类型并基于检查结果进行类型推断的技术
function printId(id: string | number): void {
if (typeof id === "string") {
console.log(`ID (string): ${id.toUpperCase()}`);
} else {
console.log(`ID (number): ${id}`);
}
}
8、类:与 ES6 的类相似,但提供了更强的类型支持、访问控制修饰符和抽象类等特性
class Person {
private name: string;
constructor(name: string) {
this.name = name;
}
greet(): void {
console.log(`Hello, ${this.name}`);
}
}
const person = new Person("Alice");
person.greet();
9、抽象类和接口的结合:抽象类和接口可以结合使用,从而提供灵活的类型定义方式,既可以定义公共行为,也可以强制实现某些方法
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log("Moving...");
}
}
class Dog extends Animal {
makeSound(): void {
console.log("Woof!");
}
}
const dog = new Dog();
dog.makeSound();
dog.move();
10、枚举:用于定义一组命名的常量,增强代码的可读性和维护性
enum Direction {
Up,
Down,
Left,
Right,
}
let dir: Direction = Direction.Up;
11、混入:允许使用混入(mixins)将多个类的功能合并到一个类中,以便代码复用
class Disposable {
isDisposed: boolean = false;
dispose() {
this.isDisposed = true;
console.log("Disposed");
}
}
class Activatable {
isActive: boolean = false;
activate() {
this.isActive = true;
console.log("Activated");
}
}
class SmartObject implements Disposable, Activatable {
isDisposed: boolean = false;
isActive: boolean = false;
dispose: () => void;
activate: () => void;
constructor() {
setInterval(() => console.log(this.isActive + " : " + this.isDisposed), 500);
}
}
applyMixins(SmartObject, [Disposable, Activatable]);
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
derivedCtor.prototype[name] = baseCtor.prototype[name];
});
});
}
const obj = new SmartObject();
obj.activate();
obj.dispose();
12. 模块化:可以使用 import 和 export 关键字进行模块化开发,提升代码组织和重用性
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
// main.ts
import { add } from './math';
console.log(add(2, 3));
13、声明文件(Declaration Files):使用声明文件(.d.ts 文件)来定义外部 JavaScript 库的类型信息,这样可以在使用第三方库时仍然享有类型检查的好处
declare module 'my-library' {
export function myFunction(x: number): number;
}
14、可选链和空值合并运算符:在访问对象属性或调用方法时,如果对象为 null 或 undefined,则返回 undefined,而不是抛出错误。空值合并运算符(??):当左侧表达式为 null 或 undefined 时,返回右侧表达式的值
let user = { name: "Alice", address: { city: "Wonderland" } };
let city = user?.address?.city; // 'Wonderland'
let name = user?.name ?? "Unknown"; // 'Alice'
1:类型安全上=>引入了静态类型系统,可以在编译阶段捕获许多常见的类型错误,减少运行时错误
2:代码维护性上=>有明确的类型定义
3:现代语言特性上=>支持最新的 ECMAScript 特性
4:更强大的IDE支持=>提供了强大的代码编辑器支持,如智能提示、代码补全、类型检查、重构工具等
5:大型项目上=>提供了模块化和类型检查功能,使得代码的可维护性、可扩展性和团队协作都得到了提升
6:现代JS兼容上=>是 JavaScript 的超集,可以与现有的 JavaScript 代码无缝集成