文档教程【免费下载链接】typescript-bookThe Concise TypeScript Book: A Concise Guide to Effective Development in TypeScript. Free and Open Source.项目地址https://gitcode.com/gh_mirrors/typ/typescript-book点击查看免费下载导读本文以开源项目 The Concise TypeScript Book一个免费开源的 TypeScript 精简指南本仓库为其镜像中「Clase / Class」章节为骨架系统讲解 TypeScript 类的全部核心语法类定义、构造函数及其重载、访问修饰符、getter/setter、自动访问器、参数属性、抽象类、泛型类、继承、静态成员、属性初始化、方法重载以及 TypeScript 5 标准装饰器的五种类型。文中所有代码示例均来自本仓库文档且会被仓库的编译校验流程tools/compile.ts在严格模式下实际编译验证读者可以直接复制运行读完你将能写出类型安全、封装良好、可复用的 TypeScript 类并掌握装饰器这一高级扩展机制。一、类的常规语法用class关键字定义类型化对象在 TypeScript 中class关键字用于定义一个类。类的成员属性与方法可以携带类型注解从而在编译期获得完整的类型检查。以本仓库文档中的基础示例为例见 es-es/book/class.md 与 book/class.mdclass Person { private name: string; private age: number; constructor(name: string, age: number) { this.name name; this.age age; } public sayHi(): void { console.log( Hello, my name is ${this.name} and I am ${this.age} years old. ); } }逐段拆解这段代码class关键字定义了名为Person的类类拥有两个私有属性name类型string和age类型number构造函数由constructor关键字定义接收name和age两个参数并将其分别赋值给对应属性类拥有一个public方法sayHi向控制台输出问候语。创建类实例使用new关键字后跟类名与括号()const myObject new Person(John Doe, 25); myObject.sayHi(); // Output: Hello, my name is John Doe and I am 25 years old.仓库事实这类带类型注解的类示例并非孤立存在——本仓库的构建管线会从所有 Markdown 文档中提取typescript代码块逐段写入临时文件并调用 TypeScript 编译器进行校验见 tools/compile.ts编译选项包含strict: true、noImplicitAny: true。这意味着文档中的每个类示例都经过了严格模式编译可作为可信的参考实现。二、构造函数初始化、重载与受限构造2.1 构造函数的作用构造函数是类中的特殊方法在创建实例时用于初始化对象的属性class Person { public name: string; public age: number; constructor(name: string, age: number) { this.name name; this.age age; } sayHello() { console.log( Hello, my name is ${this.name} and Im ${this.age} years old. ); } } const john new Person(Simon, 17); john.sayHello();2.2 构造函数重载构造函数支持重载overload。可以在类中声明多个重载签名配合一个兼容所有重载的实现签名。下面的示例利用可选参数sex?: Sex让第三个参数可省略默认值m通过??空值合并运算符提供type Sex m | f; class Person { name: string; age: number; sex: Sex; constructor(name: string, age: number, sex?: Sex); constructor(name: string, age: number, sex: Sex) { this.name name; this.age age; this.sex sex ?? m; } } const p1 new Person(Simon, 17); const p2 new Person(Alice, 22, f);2.3 多个重载签名 一个实现TypeScript 允许定义多个构造函数重载签名但只能有一个实现且该实现必须与所有重载签名兼容。实现签名通过把所有参数设为可选name?: string, age?: number来同时满足零参、单参、双参三种调用形态未提供的参数用默认值兜底class Person { name: string; age: number; constructor(); constructor(name: string); constructor(name: string, age: number); constructor(name?: string, age?: number) { this.name name ?? Unknown; this.age age ?? 0; } displayInfo() { console.log(Name: ${this.name}, Age: ${this.age}); } } const person1 new Person(); person1.displayInfo(); // Name: Unknown, Age: 0 const person2 new Person(John); person2.displayInfo(); // Name: John, Age: 0 const person3 new Person(Jane, 25); person3.displayInfo(); // Name: Jane, Age: 252.4 私有与受保护的构造函数构造函数可以被标记为private或protected从而限制其可访问性与使用方式私有构造函数private只能从类自身内部调用。常用于强制实现单例模式singleton或将实例创建限制在类内部的工厂方法中受保护构造函数protected适合定义不应被直接实例化、但允许被子类扩展的基类。class BaseClass { protected constructor() {} } class DerivedClass extends BaseClass { private value: number; constructor(value: number) { super(); this.value value; } } // 直接实例化基类会报错 // const baseObj new BaseClass(); // Error: Constructor of class BaseClass is protected. // 创建派生类实例是允许的 const derivedObj new DerivedClass(10);三、访问修饰符封装边界的三道闸门访问修饰符private、protected和public控制类成员属性、方法的可见性与可访问性是实施封装encapsulation、约束内部状态访问与修改的核心手段修饰符访问范围private仅限包含该成员的类自身内部访问protected可在包含该成员的类及其派生类中访问public无限制可从任何地方访问默认实践建议默认将成员设为private或protected只把需要对外暴露的接口设为public从而减少类内部实现的意外泄漏。四、Getter 与 Setter为属性访问注入自定义逻辑getter 和 setter 是允许为类属性定义自定义读写行为的特殊方法分别用get与set关键字声明。它们能封装对象的内部状态并在读取或赋值时附加额外逻辑校验、转换、日志等class MyClass { private _myProperty: string; constructor(value: string) { this._myProperty value; } get myProperty(): string { return this._myProperty; } set myProperty(value: string) { this._myProperty value; } }五、自动访问器Auto-AccessorsTypeScript 4.9 新特性TypeScript 4.9 引入了对 ECMAScript 即将推出的auto-accessors特性的支持本仓库 tools/tsconfig.json 中target为es2022可直接编译此类语法。它看起来像普通的类属性但使用accessor关键字声明class Animal { accessor name: string; constructor(name: string) { this.name name; } }自动访问器会被“脱糖de-sugared”为基于私有字段的get/set访问器外部操作的是一个不可直接访问的后备属性class Animal { #__name: string; get name() { return this.#__name; } set name(value: string) { this.#__name value; } constructor(name: string) { this.name name; } }自动访问器的价值在于后续你可以在不改变调用方用法仍然是obj.name的前提下随时加入读写拦截逻辑同时它天然配合装饰器体系见后文「装饰器元数据」一节。六、this关键字指向当前实例的引用在 TypeScript 中this在类的方法或构造函数内指向当前类的实例允许在自身作用域内访问和修改类的属性与方法是操作对象内部状态的统一入口class Person { private name: string; constructor(name: string) { this.name name; } public introduce(): void { console.log(Hello, my name is ${this.name}.); } } const person1 new Person(Alice); person1.introduce(); // Hello, my name is Alice.七、参数属性Parameter Properties消除样板代码参数属性允许你在构造函数参数中直接声明并初始化类属性省去「声明属性 → 参数赋值 → 手动this.x x」的重复劳动。只需在构造参数前加访问修饰符private/public/protected等class Person { constructor( private name: string, public age: number ) { // 构造函数中的 private 和 public 关键字 // 会自动声明并初始化对应的类属性。 } public introduce(): void { console.log( Hello, my name is ${this.name} and I am ${this.age} years old. ); } } const person new Person(Alice, 25); person.introduce();此处private name和public age既声明了属性又在实例化时完成初始化——代码量显著减少可读性与类型安全同时得到保证。八、抽象类定义通用契约强制子类实现抽象类abstract class主要用于继承场景它提供子类可继承的公共属性与方法同时用abstract成员强制要求子类实现特定方法从而建立「抽象基类提供共享接口与公共功能」的类层级abstract class Animal { protected name: string; constructor(name: string) { this.name name; } abstract makeSound(): void; } class Cat extends Animal { makeSound(): void { console.log(${this.name} meows.); } } const cat new Cat(Whiskers); cat.makeSound(); // Output: Whiskers meows.注意abstract方法只有签名、没有实现任何直接实例化抽象类的尝试都会产生编译错误子类必须补全其实现。九、泛型类一份代码多种类型带泛型的类可以定义可复用、可适配不同类型的容器型类。类型参数T在实例化时被具体化使内部成员属性、方法参数、返回类型全部与T绑定class ContainerT { private item: T; constructor(item: T) { this.item item; } getItem(): T { return this.item; } setItem(item: T): void { this.item item; } } const container1 new Containernumber(42); console.log(container1.getItem()); // 42 const container2 new Containerstring(Hello); container2.setItem(World); console.log(container2.getItem()); // WorldContainernumber与Containerstring是两个彼此独立、类型互不干扰的实例化类型这正是泛型类避免any泛滥、保持类型安全的关键。十、装饰器TypeScript 5 标准化的运行时扩展机制装饰器提供了一种添加元数据、修改行为、执行校验或扩展目标元素功能的机制。它们本质上是运行时执行的函数且可以同时对一个声明应用多个装饰器。10.1 版本与环境前提本仓库文档明确指出装饰器是实验性特性文中的示例仅兼容 TypeScript 5 及以上版本并使用 ES6。在 TypeScript 5 之前需要在tsconfig.json中启用experimentalDecorators属性或通过命令行参数--experimentalDecorators开启但旧版语法与下述示例不兼容。本仓库的开发环境与之匹配website/package.json 依赖typescript: ^5.9.3tools/tsconfig.json 的lib中显式包含esnext.decoratorstarget为es2022——即整套示例在该配置下可直接编译运行。注意TypeScript 5 的标准装饰器不允许装饰参数。10.2 装饰器的常见用途观察属性变化watching property changes观察方法调用watching method calls为类或成员添加额外属性/方法运行时校验runtime validation自动序列化与反序列化日志记录logging授权与认证authorization and authentication错误防护error guarding。10.3 类装饰器Class Decorators类装饰器适合扩展现有类例如为其添加属性/方法或收集类实例。下面的示例通过返回一个匿名子类为Person注入toString式能力实例化时输出对象自身的 JSON 以及装饰器上下文信息type ConstructorT {} new (...args: any[]) T; function toStringClass extends Constructor( Value: Class, context: ClassDecoratorContextClass ) { return class extends Value { constructor(...args: any[]) { super(...args); console.log(JSON.stringify(this)); console.log(JSON.stringify(context)); } }; } toString class Person { name: string; constructor(name: string) { this.name name; } greet() { return Hello, this.name; } } const person new Person(Simon); /* Logs: {name:Simon} {kind:class,name:Person} */10.4 属性装饰器Property Decorators属性装饰器用于修改属性的行为例如改变其初始化值。下面的代码让某属性始终转为大写装饰器返回一个初始化函数在字段初始化阶段对传入的原始值调用toUpperCase()function upperCaseT( target: undefined, context: ClassFieldDecoratorContextT, string ) { return function (this: T, value: string) { return value.toUpperCase(); }; } class MyClass { upperCase prop1 hello!; } console.log(new MyClass().prop1); // Logs: HELLO!10.5 方法装饰器Method Decorators方法装饰器用于改变或增强方法行为。以下是一个简单的日志装饰器在执行目标方法前后分别输出进入与退出日志并把原方法的返回值透传出去function logThis, Args extends any[], Return( target: (this: This, ...args: Args) Return, context: ClassMethodDecoratorContext This, (this: This, ...args: Args) Return ) { const methodName String(context.name); function replacementMethod(this: This, ...args: Args): Return { console.log(LOG: Entering method ${methodName}.); const result target.call(this, ...args); console.log(LOG: Exiting method ${methodName}.); return result; } return replacementMethod; } class MyClass { log sayHello() { console.log(Hello!); } } new MyClass().sayHello();运行输出LOG: Entering method sayHello. Hello! LOG: Exiting method sayHello.10.6 Getter / Setter 装饰器Getter and Setter Decoratorsgetter/setter 装饰器用于改变或增强类访问器的行为常见场景是校验属性赋值。下面示例中的range(1, 100)在每次读取 getter 时校验返回值是否落在区间内越界则抛出Invalidfunction rangeThis, Return extends number(min: number, max: number) { return function ( target: (this: This) Return, context: ClassGetterDecoratorContextThis, Return ) { return function (this: This): Return { const value target.call(this); if (value min || value max) { throw Invalid; } Object.defineProperty(this, context.name, { value, enumerable: true, }); return value; }; }; } class MyClass { private _value 0; constructor(value: number) { this._value value; } range(1, 100) get getValue(): number { return this._value; } } const obj new MyClass(10); console.log(obj.getValue); // Valid: 10 const obj2 new MyClass(999); console.log(obj2.getValue); // Throw: Invalid!10.7 装饰器元数据Decorator Metadata装饰器元数据简化了在类上应用与读取元数据的过程装饰器可以访问上下文对象上的新metadata属性其键既可以是原始值也可以是对象元数据信息随后可在类上通过Symbol.metadata获取适用于调试、序列化或基于装饰器的依赖注入等场景//ts-ignore Symbol.metadata ?? Symbol(Symbol.metadata); // Simple polyfill type Context | ClassFieldDecoratorContext | ClassAccessorDecoratorContext | ClassMethodDecoratorContext; // Context contains property metadata: DecoratorMetadata function setMetadata(_target: any, context: Context) { // 在元数据对象上设置原始值作为键 context.metadata[context.name] true; } class MyClass { setMetadata a 123; setMetadata accessor b b; setMetadata fn() {} } const metadata MyClass[Symbol.metadata]; // 获取元数据信息 console.log(JSON.stringify(metadata)); // {bar:true,baz:true,foo:true}注意本例开头提供了Symbol.metadata的简易 polyfill??以便在尚未原生支持该符号的环境中运行同时也演示了accessor自动访问器与装饰器的组合用法。十一、继承单继承 多接口实现继承是指一个类从另一个类基类/超类继承属性与方法的机制。派生类子类/子类可以通过新增属性方法、或覆写override现有成员来扩展与特化基类功能class Animal { name: string; constructor(name: string) { this.name name; } speak(): void { console.log(The animal makes a sound); } } class Dog extends Animal { breed: string; constructor(name: string, breed: string) { super(name); this.breed breed; } speak(): void { console.log(Woof! Woof!); } } // 创建基类实例 const animal new Animal(Generic Animal); animal.speak(); // The animal makes a sound // 创建派生类实例 const dog new Dog(Max, Labrador); dog.speak(); // Woof! Woof!TypeScript 有几个与继承相关的关键约束与配套手段不支持传统意义的多重继承一个类只能继承自单一基类但支持实现多个接口implements。接口定义对象结构的契约类可以实现多个接口从而从多个来源继承行为与结构interface Flyable { fly(): void; } interface Swimmable { swim(): void; } class FlyingFish implements Flyable, Swimmable { fly() { console.log(Flying...); } swim() { console.log(Swimming...); } } const flyingFish new FlyingFish(); flyingFish.fly(); flyingFish.swim();本质认知TypeScript 的class关键字与 JavaScript 一样常被视为语法糖syntactic sugar。它由 ECMAScript 2015ES6引入为基于类的对象创建提供更熟悉的语法但 TypeScript 最终编译为 JavaScript底层依然是**基于原型prototype**的机制。延伸阅读本仓库文档中还有更复杂的类组合模式。例如 es-es/book/others.md「Otros」章节讲解了mixin 类——通过applyMixins辅助函数把多个抽象类原型上的方法逐一复制到目标类原型实现「多来源组合行为」而不依赖深继承链同时该文档也用类展示了自定义错误类型class CustomError extends Error与迭代器实现class NumberIterator implements Iterablenumber可作为本节的进阶补充。十二、静态成员无需实例即可访问TypeScript 支持静态成员static members。访问静态成员时直接使用「类名 点号」无需创建任何对象实例。下面的示例用静态计数器统计实例创建次数class OfficeWorker { static memberCount: number 0; constructor(private name: string) { OfficeWorker.memberCount; } } const w1 new OfficeWorker(James); const w2 new OfficeWorker(Simon); const total OfficeWorker.memberCount; console.log(total); // 2注意静态属性属于类本身而非实例因此在构造函数中应通过OfficeWorker.memberCount而非this.memberCount访问。十三、属性初始化三种等价写法TypeScript 中初始化类属性有多种方式可按场景选用1. 内联初始化Inline——声明属性时直接赋默认值实例创建时即生效class MyClass { property1: string default value; property2: number 42; }2. 构造函数内初始化In the constructor——适合默认值依赖构造参数或需要额外逻辑的场景class MyClass { property1: string; property2: number; constructor() { this.property1 default value; this.property2 42; } }3. 构造函数参数初始化Using constructor parameters——结合参数属性与默认参数值最简洁class MyClass { constructor( private property1: string default value, public property2: number 42 ) { // 无需再显式把值赋给属性 } log() { console.log(this.property2); } } const x new MyClass(); x.log();十四、方法重载同名方法多种签名方法重载允许一个类拥有多个同名方法签名但参数类型或数量不同从而根据传入实参以不同方式调用同一方法。声明多个重载签名 一个兼容的实现签名实现内部通过类型收窄typeof判断分派逻辑class MyClass { add(a: number, b: number): number; // 重载签名 1 add(a: string, b: string): string; // 重载签名 2 add(a: number | string, b: number | string): number | string { if (typeof a number typeof b number) { return a b; } if (typeof a string typeof b string) { return a.concat(b); } throw new Error(Invalid arguments); } } const r new MyClass(); console.log(r.add(10, 5)); // Logs 15调用时 TypeScript 会根据实参类型自动选择匹配的重载签名为调用方提供精确的返回类型推断非法参数组合则在编译期即被拦截。十五、总结类的完整能力图谱围绕本仓库class.md文档可以绘制一张完整的 TypeScript 类能力图谱声明与实例化classnew属性/方法带类型注解构造函数负责初始化封装private/protected/public三修饰符 getter/setter 参数属性严格约束状态边界灵活性构造函数重载、方法重载、this、静态成员覆盖绝大多数面向对象编程需求抽象与复用抽象类模板方法契约与泛型类类型参数化复用组合与扩展单一继承 多接口实现extendsimplements进阶可参考 others.md 的 mixin 组合手法现代增强TypeScript 4.9 自动访问器accessor与 TypeScript 5 标准装饰器类 / 属性 / 方法 / getter / setter / 元数据为横切关注点日志、校验、序列化、依赖注入提供声明式方案。在仓库中验证与运行所有代码示例源自文档 es-es/book/class.md 与英文版 book/class.md仓库构建流程 tools/compile.ts 会提取文档内每个typescript代码块!-- skip --注释标记的块除外以strict: true等严格选项编译校验保证示例可直接运行本仓库支持 19 种语言的文档版本见 tools/i18n.ts 与 website/src/config/locales.ts其中es-es对应西班牙语版本各语言class.md结构一致便于对照学习。实践建议属性默认从private起步确有外部读写需求时再放宽为protected/public或提供 getter/setter构造函数重载时始终「多签名、单实现」实现签名用可选参数收窄需要「公共契约 强制实现」时优先抽象类需要「多来源行为」时优先接口组合或 mixin装饰器在 TypeScript 5 下是标准语法无需experimentalDecorators但要注意其尚不能装饰参数泛型类是构建容器、仓储、事件总线等可复用基础设施的基石配合类型约束extends效果更佳。赞分享文档教程【免费下载链接】typescript-bookThe Concise TypeScript Book: A Concise Guide to Effective Development in TypeScript. Free and Open Source.项目地址https://gitcode.com/gh_mirrors/typ/typescript-book点击查看免费下载相关推荐FunASR 中 Qwen3-ASR 离线长音频 vLLM 转写与 MOSS 说话人归属实战指南FunASR 中 Qwen3 ASR 离线长音频 vLLM 转写与 MOSS 说话人归属实战指南 本文围绕 FunASR 仓库中的离线长音频转写示例 trans文档教程TypeScript 泛型Generics完全指南从基础语法到高阶类型推断——《The Concise TypeScript Book》实战解读TypeScript 泛型Generics完全指南从基础语法到高阶类型推断——《The Concise TypeScript Book》实战解读 泛型G文档教程The Concise TypeScript Book 精读TypeScript 类Class完整指南——构造、封装、继承与装饰器实战The Concise TypeScript Book 精读TypeScript 类Class完整指南——构造、封装、继承与装饰器实战 本指南以开源仓库文档教程上一篇如何快速解决Vegas可视化库的10个常见问题ScalaSpark图表绘制终极指南下一篇Flatpickr现代化前端日期时间选择器的架构解构与生产实践创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
企业数字化 ERP 产品动态
相关推荐
Android 12 ViewCapture实战:Winscope编译与UI性能深度分析 /* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/9/25 2:32:19
使用 Hypothesis 差分测试验证性能优化:让优化版算法与原版实现保持行为一致 测试开发工具 【免费下载链接】hypothesis The property-based testing library for Python 项目地址: https://gitcode.com/gh_mirrors/hy/hypothesis 点击查看 免费下载 性能优化是软件开发中最容易出现隐蔽回归的环节:优化后的代码往往更快ÿ… · 2026/9/25 2:32:07
如何正确引用arXiv论文:BibTeX模板、版本管理与常见错误 /* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/9/25 4:26:51
USB转I2C适配器实现I2C地址扫描与100kHz时序测试 /* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/9/25 4:26:51
APL文件分析实战:从结构解析到性能根因定位 /* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/9/25 4:26:51
STM32芯片命名规则详解:从型号到选型实战指南 /* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/9/25 4:26:51
北邮数据结构实验双路径:C手写栈与C++封装的工程实践 简介:本资源是北京邮电大学《数据结构与算法》课程的全套实验与作业实践材料,面向计算机及相关专业本科生、考研复习者及算法初学者,聚焦核心数据结构实现与经典算法动手训练。压缩包共43个文件,涵盖12个C源码(如单链表… · 2026/9/25 4:26:45
创维E900V22D刷机全攻略:S905L3SB芯片兼容性解析与救砖实战 /* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/9/25 1:00:31
MQTT协议原理与Broker服务器搭建实战:从Mosquitto到EMQX /* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/9/25 1:00:37