diff --git a/.github/workflows/lint.sh b/.github/workflows/lint.sh index 3512b7ee..1ab44d06 100644 --- a/.github/workflows/lint.sh +++ b/.github/workflows/lint.sh @@ -1,6 +1,7 @@ #!/bin/bash set -e -echo "Linting all Markdown content ..." +echo "Linting Markdown and Code files ..." cd tools npm ci -npm run lint \ No newline at end of file +npm run lint +npm run lint:md \ No newline at end of file diff --git a/README-zh_CN.md b/README-zh_CN.md index 5c69a12b..4a63f3fc 100644 --- a/README-zh_CN.md +++ b/README-zh_CN.md @@ -4,24 +4,32 @@ 本书完全免费且开源。 +如果您发现这本 TypeScript 书籍很有价值并希望做出贡献,请考虑通过 PayPal 支持我的努力。谢谢! + +[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/donate/?business=QW82ZS956XLFY&no_recurring=0¤cy_code=EUR) + ## 翻译 本书已被翻译成多种语言版本,包括: -* [中文](https://github.com/gibbok/typescript-book/blob/main/README-zh_CN.md) +[中文](https://github.com/gibbok/typescript-book/blob/main/README-zh_CN.md) -## 下载 +## 下载和网站 -您还可以在这里下载 Epub 版本: +您还可以下载 Epub 版本: [https://github.com/gibbok/typescript-book/tree/main/downloads](https://github.com/gibbok/typescript-book/tree/main/downloads) +在线版本可在以下位置获得: + +[https://gibbok.github.io/typescript-book](https://gibbok.github.io/typescript-book) + ## 目录表 - [简洁的TypeScript之书](#简洁的typescript之书) - [翻译](#翻译) - - [下载](#下载) + - [下载和网站](#下载和网站) - [目录表](#目录表) - [介绍](#介绍) - [关于作者](#关于作者) @@ -34,7 +42,7 @@ - [TypeScript 入门](#typescript-入门) - [安装](#安装) - [配置](#配置) - - [TypeScript 的配置文件 tsconfig.json](#typescript-的配置文件-tsconfigjson) + - [TypeScript 的配置文件](#typescript-的配置文件) - [target](#target) - [lib](#lib) - [strict](#strict) @@ -195,6 +203,7 @@ - [Lowercase\](#lowercaset) - [Capitalize\](#capitalizet) - [Uncapitalize\](#uncapitalizet) + - [NoInfer\](#noinfert) - [其他](#其他) - [错误和异常处理](#错误和异常处理) - [混合类](#混合类) @@ -206,17 +215,17 @@ - [ES6 模块](#es6-模块) - [ES7 求幂运算符](#es7-求幂运算符) - [for-await-of 语句](#for-await-of-语句) - - [New.target](#newtarget) + - [New target 元属性](#new-target-元属性) - [动态导入表达式](#动态导入表达式) - ["tsc –watch"](#tsc-watch) - [默认声明](#默认声明) - [可选链](#可选链) - - [空合并运算符 (??)](#空合并运算符-) + - [空合并运算符](#空合并运算符) - [模板字符串类型](#模板字符串类型) - [函数重载](#函数重载) - [递归类型](#递归类型) - [递归条件类型](#递归条件类型) - - [Node.js 中的 ECMAScript 模块支持](#nodejs-中的-ecmascript-模块支持) + - [Node 中的 ECMAScript 模块支持](#node-中的-ecmascript-模块支持) - [断言函数](#断言函数) - [可变参数元组类型](#可变参数元组类型) - [装箱类型](#装箱类型) @@ -227,6 +236,7 @@ - [仅类型导入和导出](#仅类型导入和导出) - [使用声明和显式资源管理](#使用声明和显式资源管理) - [使用声明等待](#使用声明等待) + - [导入属性](#导入属性) ## 介绍 @@ -243,7 +253,7 @@ Simone Poggiali 是一位经验丰富的高级前端开发人员,自 90 年代 * 领英: [https://www.linkedin.com/in/simone-poggiali](https://www.linkedin.com/in/simone-poggiali) * GitHub: [https://github.com/gibbok](https://github.com/gibbok) -* 推特: [https://twitter.com/gibbok_coding](https://twitter.com/gibbok_coding) +* X.com: [https://x.com/gibbok_coding](https://x.com/gibbok_coding) * 电子邮箱: gibbok.coding📧gmail.com ## TypeScript简介 @@ -252,7 +262,7 @@ Simone Poggiali 是一位经验丰富的高级前端开发人员,自 90 年代 TypeScript 是一种基于 JavaScript 构建的强类型编程语言。它最初由 Anders Hejlsberg 于 2012 年设计,目前由 Microsoft 作为开源项目开发和维护。 -TypeScript 编译为 JavaScript,并且可以在任何 JavaScript 引擎(例如浏览器或服务器 Node.js)中执行。 +TypeScript 编译为 JavaScript,并且可以在任何 JavaScript 运行时(例如浏览器或服务器 Node.js)中执行。 TypeScript 支持多种编程范式,例如函数式、泛型、命令式和面向对象。TypeScript 既不是解释型语言,也不是编译型语言。 @@ -284,7 +294,7 @@ TypeScript是用`.ts`或`.tsx`文件编写的, 而JavaScript是用`.js`或`.jsx` const sum = (a, b) => a + b; ``` -该函数可以通过将文件扩展名更改为 .TypeScript 来转换和使用.ts。但是,如果同一个函数使用 TypeScript 类型进行注释,则未经编译就无法在任何 JavaScript 引擎中执行。如果未编译以下 TypeScript 代码,将会产生语法错误 +该函数可以通过将文件扩展名更改为 .TypeScript 来转换和使用.ts。但是,如果同一个函数使用 TypeScript 类型进行注释,则未经编译就无法在任何 JavaScript 运行时中执行。如果未编译以下 TypeScript 代码,将会产生语法错误 ```typescript @@ -328,7 +338,7 @@ const result = 1 + true; // 在JavaScript中, 结果等于2 ### TypeScript 代码生成 -TypeScript 编译器有两个主要职责:检查类型错误和编译为 JavaScript。这两个过程是相互独立的。类型不会影响 JavaScript 引擎中代码的执行,因为它们在编译过程中会被完全擦除。即使存在类型错误,TypeScript 仍然可以输出 JavaScript。以下是存在类型错误的 TypeScript 代码示例: +TypeScript 编译器有两个主要职责:检查类型错误和编译为 JavaScript。这两个过程是相互独立的。类型不会影响 JavaScript 运行时中代码的执行,因为它们在编译过程中会被完全擦除。即使存在类型错误,TypeScript 仍然可以输出 JavaScript。以下是存在类型错误的 TypeScript 代码示例: ```typescript @@ -523,7 +533,7 @@ tsc src/*.ts // 将 'src' 文件夹下任意的 .ts 文件编译成 JavaScript tsc app.ts util.ts --outfile index.js // 将 2 个 TypeScript 文件 (app.ts 和 util.ts) 编译成 1 个 JavaScript 文件 (index.js) ``` -### TypeScript 的配置文件 tsconfig.json +### TypeScript 的配置文件 tsconfig.json 文件用于配置 TypeScript 编译器 (tsc)。通常,它与文件一起添加到项目的根目录中package.json。 @@ -590,6 +600,7 @@ TypeScript 可以为各种模块系统生成代码,包括 UMD、System、ESNex "include"属性向编译器指示我们想要包含的文件列表。此属性允许类似 glob 的模式,例如 "\*_" 表示任何子目录,"_" 表示任何文件名,"?" 表示可选字符。 + #### exclude "exclude"属性向编译器指示不应包含在编译中的文件列表。这可以包括"node_modules"等文件或测试文件 @@ -1129,6 +1140,8 @@ npm install --save-dev @types/library-name 即使在 JavaScript 文件中,您也可以通过 `// @ts-check` 使用环境声明。 +`declare` 关键字可以为现有的 JavaScript 代码启用类型定义,而无需导入它,作为来自另一个文件或全局的类型的占位符。 + ### 属性检测和多余属性检测 TypeScript 基于结构类型系统,但过多的属性检查是 TypeScript 的一个属性,它允许它检查对象是否具有类型中指定的确切属性。 @@ -1285,7 +1298,7 @@ TypeScript 提供了控制加宽过程的方法,例如使用"const"。 For example: ```typescript -const x = 'x'; // TypeScript 将 x 的类型推断为 'x',一种较窄的类型 +const x = 'x'; // TypeScript 将 'x' 推断为带有 'const'(不可变)的字符串字面量,但将其扩展为带有 'let'(可重新赋值)的 'string'。 let y: 'y' | 'x' = 'y'; y = x; // 有效: x的类型推断为 'x' ``` @@ -1698,7 +1711,6 @@ interface B extends A { } ``` - ## 字面量类型 文字类型是来自集体类型的单个元素集,它定义了一个非常精确的值,即 JavaScript 原始数据。 @@ -1765,7 +1777,6 @@ let o = { }; ``` - ## 严格空检查 `strictNullChecks` 是一个 TypeScript 编译器选项,强制执行严格的 null 检查。启用此选项后,只有在变量和参数已使用联合类型 `null` | `undefined` 显式声明为该类型时,才可以对其进行赋值`null` 或者 `undefined`。如果变量或参数未显式声明为可为空,TypeScript 将生成错误以防止潜在的运行时错误。 @@ -3749,7 +3760,7 @@ type MyType = MyTuple[2]; // boolean #### Awaited\ -构造一个递归解包 Promise 的类型。 +构造一个递归解包 Promise 类型的类型。 ```typescript type A = Awaited>; // string @@ -4002,6 +4013,32 @@ type MyType = Capitalize<'abc'>; // "Abc" type MyType = Uncapitalize<'Abc'>; // "abc" ``` +#### NoInfer\ + +NoInfer 是一种实用类型,旨在阻止泛型函数范围内类型的自动推断。 + +示例: + +```typescript +// 泛型函数范围内类型的自动推断。 +function fn(x: T[], y: T) { + return x.concat(y); +} +const r = fn(['a', 'b'], 'c'); // 此处的类型为 ("a" | "b" | "c")[] +``` + +使用 NoInfer: + + +```typescript +// 使用 NoInfer 阻止类型推断的示例函数 +function fn2(x: T[], y: NoInfer) { + return x.concat(y); +} + +const r2 = fn2(["a", "b"], "c"); // 错误:类型为“c”的类型参数不能分配给类型为“a”|“b”的参数。 +``` + ## 其他 ### 错误和异常处理 @@ -4137,7 +4174,7 @@ WebSocket: ### 迭代器和生成器 -TypeScript 很好地支持交互器和生成器。 +TypeScript 对迭代器和生成器都提供了很好的支持。 迭代器是实现迭代器协议的对象,提供了一种逐个访问集合或序列元素的方法。它是一个包含指向迭代中下一个元素的指针的结构。他们有一个 `next()` 方法返回序列中的下一个值以及指示序列是否为 的布尔值 `done` 。 @@ -4300,7 +4337,7 @@ async function* asyncNumbers(): AsyncIterableIterator { })(); ``` -### New.target +### New target 元属性 您可以在 TypeScript 中使用 `new.target` 元属性,该属性使您能够确定是否使用 new 运算符调用函数或构造函数。它允许您检测对象是否是由于构造函数调用而创建的。 @@ -4383,7 +4420,7 @@ const person: Person = { console.log(person.address?.city); // undefined ``` -### 空合并运算符 (??) +### 空合并运算符 如果 `??` 左侧是 `null` 或者 `undefined` ,则空合并运算符返回右侧值,否则,它返回左侧值。 @@ -4474,7 +4511,7 @@ type NestedArray = [1, [2, [3, 4], 5], 6]; type FlattenedArray = Flatten; // 2 | 3 | 4 | 5 | 1 | 6 ``` -### Node.js 中的 ECMAScript 模块支持 +### Node 中的 ECMAScript 模块支持 Node.js 从 15.3.0 版本开始添加了对 ECMAScript 模块的支持,而 TypeScript 从 4.7 版本开始增加了对 Node.js 的 ECMAScript 模块支持。可以通过将 `tsconfig.json` 文件中的`module`属性的值设置为 `nodenext` 来启用此支持。这是一个例子: @@ -4912,3 +4949,21 @@ Connection closed. ``` 语句中允许使用"using"和"await using"声明:"for"、"for-in"、"for-of"、"for-await-of"、"switch"。 + +### 导入属性 + +TypeScript 5.3 的导入属性(导入标签)告诉运行时如何处理模块(JSON 等)。这通过确保干净的导入来提高安全性,并与内容安全策略 (CSP) 保持一致,以实现更安全的资源加载。TypeScript 确保它们有效,但让运行时处理它们的解释以进行特定的模块处理。 + +示例: + + +```typescript +import config from './config.json' with { type: 'json' }; +``` + +使用动态导入: + + +```typescript +const config = import("./config.json", { with: { type: "json" } }) +``` diff --git a/README.md b/README.md index 6c47bcd1..4dbfb91f 100644 --- a/README.md +++ b/README.md @@ -12,20 +12,24 @@ If you found this TypeScript book valuable and wish to contribute, consider supp This book has been translated into several language versions, including: -* [Chinese](https://github.com/gibbok/typescript-book/blob/main/README-zh_CN.md) +[Chinese](https://github.com/gibbok/typescript-book/blob/main/README-zh_CN.md) -## Downloads +## Downloads and website -You can also download the Epub version here: +You can also download the Epub version: [https://github.com/gibbok/typescript-book/tree/main/downloads](https://github.com/gibbok/typescript-book/tree/main/downloads) +An online version is available at: + +[https://gibbok.github.io/typescript-book](https://gibbok.github.io/typescript-book) + ## Table of Contents - [The Concise TypeScript Book](#the-concise-typescript-book) - [Translations](#translations) - - [Downloads](#downloads) + - [Downloads and website](#downloads-and-website) - [Table of Contents](#table-of-contents) - [Introduction](#introduction) - [About the Author](#about-the-author) @@ -38,7 +42,7 @@ You can also download the Epub version here: - [Getting Started With TypeScript](#getting-started-with-typescript) - [Installation](#installation) - [Configuration](#configuration) - - [TypeScript Configuration File ​​tsconfig.json](#typescript-configuration-file-tsconfigjson) + - [TypeScript Configuration File](#typescript-configuration-file) - [target](#target) - [lib](#lib) - [strict](#strict) @@ -148,7 +152,7 @@ You can also download the Epub version here: - [Constructor](#constructor) - [Private and Protected Constructors](#private-and-protected-constructors) - [Access Modifiers](#access-modifiers) - - [Get \& Set](#get--set) + - [Get and Set](#get-and-set) - [Auto-Accessors in Classes](#auto-accessors-in-classes) - [this](#this) - [Parameter Properties](#parameter-properties) @@ -198,6 +202,7 @@ You can also download the Epub version here: - [Lowercase\](#lowercaset) - [Capitalize\](#capitalizet) - [Uncapitalize\](#uncapitalizet) + - [NoInfer\](#noinfert) - [Others](#others) - [Errors and Exception Handling](#errors-and-exception-handling) - [Mixin classes](#mixin-classes) @@ -209,18 +214,18 @@ You can also download the Epub version here: - [ES6 Modules](#es6-modules) - [ES7 Exponentiation Operator](#es7-exponentiation-operator) - [The for-await-of Statement](#the-for-await-of-statement) - - [New.target](#newtarget) + - [New target meta-property](#new-target-meta-property) - [Dynamic Import Expressions](#dynamic-import-expressions) - ["tsc –watch"](#tsc-watch) - - [Non-null Assertion Operator (Postfix !)](#non-null-assertion-operator-postfix-) + - [Non-null Assertion Operator](#non-null-assertion-operator) - [Defaulted declarations](#defaulted-declarations) - [Optional Chaining](#optional-chaining) - - [Nullish coalescing operator (??)](#nullish-coalescing-operator-) + - [Nullish coalescing operator](#nullish-coalescing-operator) - [Template Literal Types](#template-literal-types) - [Function overloading](#function-overloading) - [Recursive Types](#recursive-types) - [Recursive Conditional Types](#recursive-conditional-types) - - [ECMAScript Module Support in Node.js](#ecmascript-module-support-in-nodejs) + - [ECMAScript Module Support in Node](#ecmascript-module-support-in-node) - [Assertion Functions](#assertion-functions) - [Variadic Tuple Types](#variadic-tuple-types) - [Boxed types](#boxed-types) @@ -231,7 +236,9 @@ You can also download the Epub version here: - [Type-Only Imports and Export](#type-only-imports-and-export) - [using declaration and Explicit Resource Management](#using-declaration-and-explicit-resource-management) - [await using declaration](#await-using-declaration) + - [Import Attributes](#import-attributes) + ## Introduction Welcome to The Concise TypeScript Book! This guide equips you with essential knowledge and practical skills for effective TypeScript development. Discover key concepts and techniques to write clean, robust code. Whether you're a beginner or an experienced developer, this book serves as both a comprehensive guide and a handy reference for leveraging TypeScript's power in your projects. @@ -246,7 +253,7 @@ You can reach Simone Poggiali on the following platforms: * LinkedIn: [https://www.linkedin.com/in/simone-poggiali](https://www.linkedin.com/in/simone-poggiali) * GitHub: [https://github.com/gibbok](https://github.com/gibbok) -* Twitter: [https://twitter.com/gibbok_coding](https://twitter.com/gibbok_coding) +* X.com: [https://x.com/gibbok_coding](https://x.com/gibbok_coding) * Email: gibbok.coding📧gmail.com ## TypeScript Introduction @@ -255,7 +262,7 @@ You can reach Simone Poggiali on the following platforms: TypeScript is a strongly typed programming language that builds on JavaScript. It was originally designed by Anders Hejlsberg in 2012 and is currently developed and maintained by Microsoft as an open source project. -TypeScript compiles to JavaScript and can be executed in any JavaScript engine (e.g., a browser or server Node.js). +TypeScript compiles to JavaScript and can be executed in any JavaScript runtime (e.g., a browser or server Node.js). TypeScript supports multiple programming paradigms such as functional, generic, imperative, and object-oriented. TypeScript is neither an interpreted nor a compiled language. @@ -288,7 +295,7 @@ For instance, consider a function in a JavaScript file with the `.js` extension, const sum = (a, b) => a + b; ``` -The function can be converted and used in TypeScript by changing the file extension to `.ts`. However, if the same function is annotated with TypeScript types, it cannot be executed in any JavaScript engine without compilation. The following TypeScript code will produce a syntax error if it is not compiled: +The function can be converted and used in TypeScript by changing the file extension to `.ts`. However, if the same function is annotated with TypeScript types, it cannot be executed in any JavaScript runtime without compilation. The following TypeScript code will produce a syntax error if it is not compiled: ```typescript @@ -332,7 +339,7 @@ This error occurs because TypeScript strictly enforces type compatibility, and i ### TypeScript Code Generation -The TypeScript compiler has two main responsibilities: checking for type errors and compiling to JavaScript. These two processes are independent of each other. Types do not affect the execution of the code in a JavaScript engine, as they are completely erased during compilation. TypeScript can still output JavaScript even in the presence of type errors. +The TypeScript compiler has two main responsibilities: checking for type errors and compiling to JavaScript. These two processes are independent of each other. Types do not affect the execution of the code in a JavaScript runtime, as they are completely erased during compilation. TypeScript can still output JavaScript even in the presence of type errors. Here is an example of TypeScript code with a type error: @@ -534,7 +541,7 @@ tsc src/*.ts // Compile any .ts files under the 'src' folder to JavaScript tsc app.ts util.ts --outfile index.js // Compile two TypeScript files (app.ts and util.ts) into a single JavaScript file (index.js) ``` -### TypeScript Configuration File ​​tsconfig.json +### TypeScript Configuration File A tsconfig.json file is used to configure the TypeScript Compiler (tsc). Usually, it is added to the root of the project, together with the `package.json` file. @@ -1138,6 +1145,8 @@ For your defined Ambient Declarations, you can import using the "triple-slash" r You can use Ambient Declarations even within JavaScript files using `// @ts-check`. +The `declare` keyword enables type definitions for existing JavaScript code without importing it, serving as a placeholder for types from another file or globally. + ### Property Checking and Excess Property Checking TypeScript is based on a structural type system but excess property checking is a property of TypeScript which allows it to check whether an object has the exact properties specified in the type. @@ -2324,7 +2333,7 @@ console.log(myDict['a']); // Returns a Type from Value in TypeScript refers to the automatic inference of a type from a value or expression through type inference. ```typescript -const x = 'x'; // TypeScript can automatically infer that the type of the message variable is string +const x = 'x'; // TypeScript infers 'x' as a string literal with 'const' (immutable), but widens it to 'string' with 'let' (reassignable). ``` ## Type from Func Return @@ -3002,7 +3011,7 @@ The `protected` modifier allows access to the class member within the containing The `public` modifier provides unrestricted access to the class member, allowing it to be accessed from anywhere." -### Get & Set +### Get and Set Getters and setters are special methods that allow you to define custom access and modification behavior for class properties. They enable you to encapsulate the internal state of an object and provide additional logic when getting or setting the values of properties. In TypeScript, getters and setters are defined using the `get` and `set` keywords respectively. Here's an example: @@ -3784,7 +3793,7 @@ Several built-in utility types can be used to manipulate types, below a list of #### Awaited\ -Constructs a type recursively unwrap Promises. +Constructs a type that recursively unwraps Promise types. ```typescript type A = Awaited>; // string @@ -4037,6 +4046,32 @@ Uncapitalize the name of the input type T. type MyType = Uncapitalize<'Abc'>; // "abc" ``` +#### NoInfer\ + +NoInfer is a utility type designed to block the automatic inference of types within the scope of a generic function. + +Example: + +```typescript +// Automatic inference of types within the scope of a generic function. +function fn(x: T[], y: T) { + return x.concat(y); +} +const r = fn(['a', 'b'], 'c'); // Type here is ("a" | "b" | "c")[] +``` + +With NoInfer: + + +```typescript +// Example function that uses NoInfer to prevent type inference +function fn2(x: T[], y: NoInfer) { + return x.concat(y); +} + +const r2 = fn2(['a', 'b'], 'c'); // Error: Type Argument of type '"c"' is not assignable to parameter of type '"a" | "b"'. +``` + ## Others ### Errors and Exception Handling @@ -4172,7 +4207,7 @@ WebSocket: ### Iterators and Generators -Both Interators and Generators are well supported in TypeScript. +Both Iterators and Generators are well supported in TypeScript. Iterators are objects that implement the iterator protocol, providing a way to access elements of a collection or sequence one by one. It is a structure that contains a pointer to the next element in the iteration. They have a `next()` method that returns the next value in the sequence along with a boolean indicating if the sequence is `done`. @@ -4337,7 +4372,7 @@ async function* asyncNumbers(): AsyncIterableIterator { })(); ``` -### New.target +### New target meta-property You can use in TypeScript the `new.target` meta-property which enables you to determine if a function or constructor was invoked using the new operator. It allows you to detect whether an object was created as a result of a constructor call. @@ -4387,7 +4422,7 @@ tsc --watch Starting from TypeScript version 4.9, file monitoring primarily relies on file system events, automatically resorting to polling if an event-based watcher cannot be established. -### Non-null Assertion Operator (Postfix !) +### Non-null Assertion Operator The Non-null Assertion Operator (Postfix !) also called Definite Assignment Assertions is a TypeScript feature that allows you to assert that a variable or property is not null or undefined, even if TypeScript's static type analysis suggests that it might be. With this feature it is possible to remove any explicit checking. @@ -4434,7 +4469,7 @@ const person: Person = { console.log(person.address?.city); // undefined ``` -### Nullish coalescing operator (??) +### Nullish coalescing operator The nullish coalescing operator `??` returns the right-hand side value if the left-hand side is `null` or `undefined`; otherwise, it returns the left-hand side value. @@ -4527,7 +4562,7 @@ type NestedArray = [1, [2, [3, 4], 5], 6]; type FlattenedArray = Flatten; // 2 | 3 | 4 | 5 | 1 | 6 ``` -### ECMAScript Module Support in Node.js +### ECMAScript Module Support in Node Node.js added support for ECMAScript Modules starting from version 15.3.0, and TypeScript has had ECMAScript Module Support for Node.js since version 4.7. This support can be enabled by using the `module` property with the value `nodenext` in the tsconfig.json file. Here's an example: @@ -4764,7 +4799,7 @@ console.log(obj['key-b']); // 456 ### The satisfies Operator -The `satisfies` allows you to check if a given type satisfies a specific interface or condition. In other words, it ensures that a type has all the required properties and methods of a specific interface. It is a way to ensure a variable fits into a definition of a type +The `satisfies` allows you to check if a given type satisfies a specific interface or condition. In other words, it ensures that a type has all the required properties and methods of a specific interface. It is a way to ensure a variable fits into a definition of a type. Here is an example: @@ -4965,3 +5000,21 @@ Connection closed. ``` The `using` and `await using` declarations are allowed in Statements: `for`, `for-in`, `for-of`, `for-await-of`, `switch`. + +### Import Attributes + +TypeScript 5.3's Import Attributes (labels for imports) tell the runtime how to handle modules (JSON, etc.). This improves security by ensuring clear imports and aligns with Content Security Policy (CSP) for safer resource loading. TypeScript ensures they are valid but lets the runtime handle their interpretation for specific module handling. + +Example: + + +```typescript +import config from './config.json' with { type: 'json' }; +``` + +with dynamic import: + + +```typescript +const config = import('./config.json', { with: { type: 'json' } }); +``` diff --git a/downloads/typescript-book-zh_CN.epub b/downloads/typescript-book-zh_CN.epub index c2498e54..2e75d9ce 100644 Binary files a/downloads/typescript-book-zh_CN.epub and b/downloads/typescript-book-zh_CN.epub differ diff --git a/downloads/typescript-book-zh_CN.pdf b/downloads/typescript-book-zh_CN.pdf new file mode 100644 index 00000000..57384dfd Binary files /dev/null and b/downloads/typescript-book-zh_CN.pdf differ diff --git a/downloads/typescript-book.epub b/downloads/typescript-book.epub index ba241dc4..a1856c21 100644 Binary files a/downloads/typescript-book.epub and b/downloads/typescript-book.epub differ diff --git a/downloads/typescript-book.pdf b/downloads/typescript-book.pdf new file mode 100644 index 00000000..751adec2 Binary files /dev/null and b/downloads/typescript-book.pdf differ diff --git a/tools/Makefile b/tools/Makefile index 3b3eece4..2ffe916e 100644 --- a/tools/Makefile +++ b/tools/Makefile @@ -7,5 +7,11 @@ check: website: python3 ./make-website-content.py +website-deploy: + cd ../website && npm run deploy + +website-preview: + cd ../website && npm run build && npm run preview + books: ./make-books.sh \ No newline at end of file diff --git a/tools/README.md b/tools/README.md index c6c2bd9c..5b5f990f 100644 --- a/tools/README.md +++ b/tools/README.md @@ -6,19 +6,29 @@ If you're working with Markdown books, here are some essential tools and command Before you begin, ensure you have Node.js installed. To set up the required dependencies, use the following commands: +In folder `tools` and `website`: + ```shell nvm use npm install ``` +```shell +brew install pandoc +brew install epubcheck +brew install --cask calibre +``` + ## Commands Use `make` to run the main commands: -- `make format`: Format Markdown files for books. -- `make check`: Run several checks to ensure the Markdown files are valid. -- `make website`: Create different Markdown pages for the website. -- `make books`: Create .epub books. +* `make format`: Format Markdown files for books. +* `make check`: Run several checks to ensure the Markdown files are valid. +* `make website`: Create different Markdown pages for the website. +* `make website-preview`: Build and preview website locally. +* `make website-deploy`: Build and deploy website to GitHub Pages. +* `make books`: Create .epub books. ### Formatting @@ -52,6 +62,14 @@ For a comprehensive process that includes linting all Markdown files, applying P npm run check ``` +The project uses the [Markdown All in One](https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one)Visual Studio Code extension to automatically update the table of contents. + +Use the following command to install it: + +```shell +code --install-extension yzhang.markdown-all-in-one +``` + ### Skipping Compilation If you have specific snippets in the Markdown files that you don't want to compile, simply add `` just before the TypeScript demarcation for those snippets. @@ -67,3 +85,31 @@ make-books.sh After generating the Epub files, thoroughly test them, and once you're satisfied with the results, commit the changes. These tools will assist you in efficiently working with Markdown books and ensure a smooth and organized process. Happy writing! + +## Debug EPUB Issues + +To debug the EPUB files you create, follow these steps: + +First, download and install Sigil. You can use the following command to install Sigil: + +```shell +brew install --cask sigil +``` + +Next, run an EPUB check to validate your EPUB file. For example: + +```shell +epubcheck ../downloads/typescript-book.epub +``` + +Finally, open the EPUB file using Sigil for detailed inspection. + +## How to Contribute to This E-Book + +To contribute to this e-book, follow these steps: + +* Update the main Markdown file with your changes. +* Run `make check` to ensure the linter and other checks pass. +* Preview the website locally with `make website-preview` to make sure it works as expected. +* Generate the e-books by running `make books`. +* Submit your PR and share your awesome contributions! diff --git a/tools/make-books.sh b/tools/make-books.sh index 1a5f7ea3..5c69eb4f 100755 --- a/tools/make-books.sh +++ b/tools/make-books.sh @@ -1,16 +1,50 @@ #!/bin/bash -echo "Making ebooks ..." -DIR_DOWNLOADS=downloads +DIR_DOWNLOADS="downloads" + +INPUT_EN="README" +INPUT_CN="README-zh_CN" + +OUTPUT_EN="typescript-book" +OUTPUT_CN="typescript-book-zh_CN" + +AUTHOR="Simone Poggiali" +TITLE_EN="The Concise TypeScript Book" +TITLE_CN="# 简洁的TypeScript之书" cd ../ + +echo "Making ebooks ..." + +# Check dependencies if command -v pandoc &>/dev/null; then echo "pandoc is installed" else echo "You need to install pandoc. Please visit: https://pandoc.org/installing.html" exit 1 fi +if command -v epubcheck &>/dev/null; then + echo "epubcheck is installed" +else + echo "You need to install epubcheck. Please visit: https://www.w3.org/publishing/epubcheck/docs/installation/" + exit 1 +fi +if command -v ebook-convert &>/dev/null; then + echo "calibre is installed" +else + echo "You need to install calibre. Please visit: https://calibre-ebook.com/download" + exit 1 +fi + +# Generate eBooks +pandoc -o $DIR_DOWNLOADS/$OUTPUT_EN.epub --metadata title="$TITLE_EN" --metadata author="$AUTHOR" -s $INPUT_EN.md +pandoc -o $DIR_DOWNLOADS/$OUTPUT_CN.epub --metadata title="$TITLE_CN" --metadata author="$AUTHOR" -s $INPUT_CN.md + +# Validate eBooks +epubcheck $DIR_DOWNLOADS/$OUTPUT_CN.epub +epubcheck $DIR_DOWNLOADS/$OUTPUT_CN.epub -pandoc -o $DIR_DOWNLOADS/typescript-book.epub --metadata title="The Concise TypeScript Book" --metadata author="Simone Poggiali" -s README.md -pandoc -o $DIR_DOWNLOADS/typescript-book-zh_CN.epub --metadata title="# 简洁的TypeScript之书" --metadata author="Simone Poggiali" -s README-zh_CN.md +# Generate PDFs +ebook-convert $DIR_DOWNLOADS/$OUTPUT_EN.epub $DIR_DOWNLOADS/$OUTPUT_EN.pdf --pdf-page-numbers +ebook-convert $DIR_DOWNLOADS/$OUTPUT_CN.epub $DIR_DOWNLOADS/$OUTPUT_CN.pdf --pdf-page-numbers echo "Books were created. Please commit!" \ No newline at end of file diff --git a/tools/make-website-content.py b/tools/make-website-content.py index fc5edf65..2d6c083d 100644 --- a/tools/make-website-content.py +++ b/tools/make-website-content.py @@ -7,6 +7,8 @@ import os import re import shutil +from typing import List + # INPUT_FILE_PATH = "./test-md/README.md" # OUTPUT_DIR_PATH = "./test-md/en" @@ -20,38 +22,38 @@ OUTPUT_DIR_PATH_CN = "../website/src/content/docs/zh-cn/book" -def manage_output_dir(path): +def manage_output_dir(path: str) -> None: if os.path.exists(path): shutil.rmtree(path) os.makedirs(path) -def read_content_file(path): +def read_content_file(path: str) -> List[str]: with open(path, "r") as file: lines = file.readlines() return lines -def make_file_name(name): +def make_file_name(name: str) -> str: content_sanitized = re.sub(r"[^a-zA-Z0-9]+", "-", name.lower()).strip("-") return f"{content_sanitized}" -def make_output_path(output_dir, file_name): +def make_output_path(output_dir: str, file_name: str): return f"{output_dir}/{file_name}.md" -def is_line_header_1_to_2(line): +def is_line_header_1_to_2(line: str) -> bool: return re.match(r"^(#{1,2})\s+(.+)", line) -def make_file_output_path(output_dir, name): +def make_file_output_path(output_dir: str, name: str) -> str: file_name = make_file_name(name) output_file_path = make_output_path(output_dir, file_name) return output_file_path -def make_markdown_page_metadata(order, header): +def make_markdown_page_metadata(order: int, header: str) -> List[str]: return [ "---\n", f"title: {header}\n", @@ -63,31 +65,33 @@ def make_markdown_page_metadata(order, header): ] -def save_content_to_file(path, lines): +def save_content_to_file(path: str, lines: List[str]): with open(path, "w") as output_file: output_file.writelines(lines) -def save_pages_to_files(data_pages, master_headers, output_dir): +def save_pages_to_files( + data_pages: List[List[str]], master_headers: List[str], output_dir: str +) -> None: for index, header in enumerate(master_headers): file = make_file_output_path(output_dir, header) save_content_to_file(file, data_pages[index]) -def find_master_headers(lines): +def find_master_headers(lines: List[str]) -> List[str]: headers = [x for x in lines if is_line_header_1_to_2(x)] headers_clean = list(map(lambda x: make_file_name(x), headers)) return headers_clean -def remove_markdown_anchors(markdown_text): +def remove_markdown_anchors(markdown_text: str): pattern = r"\[(.*?)\]\(#[^\)]*\)" replacement = r"\1" transformed_text = re.sub(pattern, replacement, markdown_text) return transformed_text -def split_content_by_headings(lines): +def split_content_by_headings(lines: List[str]): current_content = [] in_page = False header_index = -1 @@ -120,20 +124,20 @@ def split_content_by_headings(lines): return content_result -content_lines_master = read_content_file(INPUT_FILE_PATH) -master_headers = find_master_headers(content_lines_master) +def process(base_input_path, input_lang_path: str, base_output_path: str) -> None: + manage_output_dir(base_output_path) + content_lines_master = read_content_file(base_input_path) + master_headers = find_master_headers(content_lines_master) -def process(base_input, base_output): - manage_output_dir(base_output) - content_lines = read_content_file(base_input) + content_lines = read_content_file(input_lang_path) data_pages = split_content_by_headings( content_lines, ) - save_pages_to_files(data_pages, master_headers, base_output) - print(f"A total of: {len(master_headers)} files were at: {base_output}") + save_pages_to_files(data_pages, master_headers, base_output_path) + print(f"A total of: {len(master_headers)} files were at: {base_output_path}") -process(INPUT_FILE_PATH, OUTPUT_DIR_PATH) +process(INPUT_FILE_PATH, INPUT_FILE_PATH, OUTPUT_DIR_PATH) -process(INPUT_FILE_PATH_CN, OUTPUT_DIR_PATH_CN) +process(INPUT_FILE_PATH, INPUT_FILE_PATH_CN, OUTPUT_DIR_PATH_CN) diff --git a/tools/package-lock.json b/tools/package-lock.json index a389b18f..198f32ca 100644 --- a/tools/package-lock.json +++ b/tools/package-lock.json @@ -17,9 +17,9 @@ "fs-extra": "^11.1.1", "markdownlint-cli": "^0.35.0", "marked": "^5.1.0", - "prettier": "^3.0.3", + "prettier": "^3.3.0", "ts-node": "^10.9.1", - "typescript": "^5.2.2" + "typescript": "^5.4.5" } }, "node_modules/@cspotcode/source-map-support": { @@ -331,9 +331,9 @@ "dev": true }, "node_modules/fs-extra": { - "version": "11.1.1", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.1.1.tgz", - "integrity": "sha512-MGIE4HOvQCeUCzmlHs0vXpih4ysz4wg9qiSAu6cd42lVwPbTM1TjV7RusoyQqMmk/95gdQZX72u+YW+c3eEpFQ==", + "version": "11.2.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.2.0.tgz", + "integrity": "sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw==", "dev": true, "dependencies": { "graceful-fs": "^4.2.0", @@ -627,9 +627,9 @@ } }, "node_modules/prettier": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.0.3.tgz", - "integrity": "sha512-L/4pUDMxcNa8R/EthV08Zt42WBO4h1rarVtK0K+QJG0X187OLo7l699jWw0GKuwzkPQ//jMFA/8Xm6Fh3J/DAg==", + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.3.0.tgz", + "integrity": "sha512-J9odKxERhCQ10OC2yb93583f6UnYutOeiV5i0zEDS7UGTdUt0u+y8erxl3lBKvwo/JHyyoEdXjwp4dke9oyZ/g==", "dev": true, "bin": { "prettier": "bin/prettier.cjs" @@ -841,9 +841,9 @@ } }, "node_modules/typescript": { - "version": "5.2.2", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.2.2.tgz", - "integrity": "sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w==", + "version": "5.4.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", + "integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==", "dev": true, "bin": { "tsc": "bin/tsc", diff --git a/tools/package.json b/tools/package.json index df54f137..f9275159 100644 --- a/tools/package.json +++ b/tools/package.json @@ -22,8 +22,8 @@ "fs-extra": "^11.1.1", "markdownlint-cli": "^0.35.0", "marked": "^5.1.0", - "prettier": "^3.0.3", + "prettier": "^3.3.0", "ts-node": "^10.9.1", - "typescript": "^5.2.2" + "typescript": "^5.4.5" } } diff --git a/website/astro.config.mjs b/website/astro.config.mjs index 2f4303d7..8e717b09 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -3,9 +3,24 @@ import starlight from '@astrojs/starlight'; // https://astro.build/config export default defineConfig({ - site: 'https://gibbok.github.io/typescript-book', + site: 'https://gibbok.github.io', + base: '/typescript-book', + build: { + assets: 'app_assets', + }, integrations: [ starlight({ + head: [ + { + tag: 'script', + attrs: { + defer: true, + src: 'https://static.cloudflareinsights.com/beacon.min.js', + 'data-cf-beacon': + '{"token": "949aed66281e40378ac479993d699897"}', + }, + }, + ], title: 'TypeScript Book', customCss: ['./src/styles/custom.css'], social: { diff --git a/website/package-lock.json b/website/package-lock.json index 9390d09c..1fc886cb 100644 --- a/website/package-lock.json +++ b/website/package-lock.json @@ -13,6 +13,9 @@ "astro": "^4.0.1", "sharp": "^0.32.5", "typescript": "^5.3.3" + }, + "devDependencies": { + "gh-pages": "^6.1.1" } }, "node_modules/@ampproject/remapping": { @@ -2013,6 +2016,27 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/array-union": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", + "integrity": "sha512-Dxr6QJj/RdU/hCaBjOfxW+q6lyuVE6JFWIrAUpuOOhoJJoQ99cUn3igRaHVB5P9WrgFVN0FfArM3x0cueOU8ng==", + "dev": true, + "dependencies": { + "array-uniq": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/array-uniq": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", + "integrity": "sha512-MNha4BWQ6JbwhFhj03YK552f7cb3AzoE8SzeljgChvL1dl3IcvggXVz1DilzySZkCja+CXuZbdW7yATchWn8/Q==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/astring": { "version": "1.8.6", "resolved": "https://registry.npmjs.org/astring/-/astring-1.8.6.tgz", @@ -2112,6 +2136,12 @@ "astro": "^3.3.0 || ^4.0.0-beta" } }, + "node_modules/async": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.5.tgz", + "integrity": "sha512-baNZyqaaLhyLVKm/DlvdW051MSgO6b8eVfIezl9E5PqWxFgzLm/wQntEW4zOytVburDEr0JlALEpdOFwvErLsg==", + "dev": true + }, "node_modules/axobject-query": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.0.0.tgz", @@ -2134,6 +2164,12 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true + }, "node_modules/base-64": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/base-64/-/base-64-1.0.0.tgz", @@ -2257,6 +2293,16 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, "node_modules/braces": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", @@ -2663,11 +2709,32 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/commander": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-11.1.0.tgz", + "integrity": "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==", + "dev": true, + "engines": { + "node": ">=16" + } + }, "node_modules/common-ancestor-path": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/common-ancestor-path/-/common-ancestor-path-1.0.1.tgz", "integrity": "sha512-L3sHRo1pXXEqX8VU28kfgUY+YGsk09hPqZiZmLacNib6XNTCM8ubYeT7ryXQw8asB1sKgcU5lkB7ONug08aB8w==" }, + "node_modules/commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", + "dev": true + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -2857,6 +2924,12 @@ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.632.tgz", "integrity": "sha512-JGmudTwg7yxMYvR/gWbalqqQiyu7WTFv2Xu3vw4cJHXPFxNgAk0oy8UHaer8nLF4lZJa+rNoj6GsrKIVJTV6Tw==" }, + "node_modules/email-addresses": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/email-addresses/-/email-addresses-5.0.0.tgz", + "integrity": "sha512-4OIPYlA6JXqtVn8zpHpGiI7vE6EQOAg16aGnDMIAlZVinnoZ8208tW1hAbjWydgN/4PLTT9q+O1K6AH/vALJGw==", + "dev": true + }, "node_modules/emmet": { "version": "2.4.6", "resolved": "https://registry.npmjs.org/emmet/-/emmet-2.4.6.tgz", @@ -3121,6 +3194,32 @@ "reusify": "^1.0.4" } }, + "node_modules/filename-reserved-regex": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/filename-reserved-regex/-/filename-reserved-regex-2.0.0.tgz", + "integrity": "sha512-lc1bnsSr4L4Bdif8Xb/qrtokGbq5zlsms/CYH8PP+WtCkGNF65DPiQY8vG3SakEdRn8Dlnm+gW/qWKKjS5sZzQ==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/filenamify": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/filenamify/-/filenamify-4.3.0.tgz", + "integrity": "sha512-hcFKyUG57yWGAzu1CMt/dPzYZuv+jAJUT85bL8mrXvNe6hWj6yEHEc4EdcgiA6Z3oi1/9wXJdZPXF2dZNgwgOg==", + "dev": true, + "dependencies": { + "filename-reserved-regex": "^2.0.0", + "strip-outer": "^1.0.1", + "trim-repeated": "^1.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/fill-range": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", @@ -3132,6 +3231,23 @@ "node": ">=8" } }, + "node_modules/find-cache-dir": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-3.3.2.tgz", + "integrity": "sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==", + "dev": true, + "dependencies": { + "commondir": "^1.0.1", + "make-dir": "^3.0.2", + "pkg-dir": "^4.1.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/avajs/find-cache-dir?sponsor=1" + } + }, "node_modules/find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -3169,6 +3285,26 @@ "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==" }, + "node_modules/fs-extra": { + "version": "11.2.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.2.0.tgz", + "integrity": "sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw==", + "dev": true, + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -3228,6 +3364,28 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/gh-pages": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/gh-pages/-/gh-pages-6.1.1.tgz", + "integrity": "sha512-upnohfjBwN5hBP9w2dPE7HO5JJTHzSGMV1JrLrHvNuqmjoYHg6TBrCcnEoorjG/e0ejbuvnwyKMdTyM40PEByw==", + "dev": true, + "dependencies": { + "async": "^3.2.4", + "commander": "^11.0.0", + "email-addresses": "^5.0.0", + "filenamify": "^4.3.0", + "find-cache-dir": "^3.3.1", + "fs-extra": "^11.1.1", + "globby": "^6.1.0" + }, + "bin": { + "gh-pages": "bin/gh-pages.js", + "gh-pages-clean": "bin/gh-pages-clean.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/github-from-package": { "version": "0.0.0", "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", @@ -3238,6 +3396,26 @@ "resolved": "https://registry.npmjs.org/github-slugger/-/github-slugger-2.0.0.tgz", "integrity": "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw==" }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "dev": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/glob-parent": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", @@ -3257,6 +3435,31 @@ "node": ">=4" } }, + "node_modules/globby": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-6.1.0.tgz", + "integrity": "sha512-KVbFv2TQtbzCoxAnfD6JcHZTYCzyliEaaeM/gH8qQdkKr5s0OP9scEgvdcngyk7AVdY6YVW/TJHd+lQ/Df3Daw==", + "dev": true, + "dependencies": { + "array-union": "^1.0.1", + "glob": "^7.0.3", + "object-assign": "^4.0.1", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/globby/node_modules/pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/graceful-fs": { "version": "4.2.11", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", @@ -3639,6 +3842,16 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "dev": true, + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", @@ -3931,6 +4144,18 @@ "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-2.3.1.tgz", "integrity": "sha512-H8jvkz1O50L3dMZCsLqiuB2tA7muqbSg1AtGEkN0leAqGjsUzDJir3Zwr02BhqdcITPg3ei3mZ+HjMocAknhhg==" }, + "node_modules/jsonfile": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", + "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "dev": true, + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, "node_modules/kind-of": { "version": "6.0.3", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", @@ -4054,6 +4279,30 @@ "node": ">=12" } }, + "node_modules/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dev": true, + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-dir/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, "node_modules/markdown-extensions": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/markdown-extensions/-/markdown-extensions-2.0.0.tgz", @@ -5146,6 +5395,18 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, "node_modules/minimist": { "version": "1.2.8", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", @@ -5297,6 +5558,15 @@ "url": "https://github.com/fb55/nth-check?sponsor=1" } }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -5532,6 +5802,15 @@ "node": ">=8" } }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", @@ -5584,6 +5863,27 @@ "node": ">=6" } }, + "node_modules/pinkie": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", + "integrity": "sha512-MnUuEycAemtSaeFSjXKW/aroV7akBbY+Sv+RkyqFjgAe73F+MR0TBWKBRDkmfWq/HiFmdavfZ1G7h4SPZXaCSg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pinkie-promise": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", + "integrity": "sha512-0Gni6D4UcLTbv9c57DfxDGdr41XfgUjqWZu492f0cIGr16zDU06BWP/RAEvOuo7CQ0CNjHaLlM59YJJFm3NWlw==", + "dev": true, + "dependencies": { + "pinkie": "^2.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/pkg-dir": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", @@ -7203,6 +7503,18 @@ "node": ">=0.10.0" } }, + "node_modules/strip-outer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/strip-outer/-/strip-outer-1.0.1.tgz", + "integrity": "sha512-k55yxKHwaXnpYGsOzg4Vl8+tDrWylxDEpknGjhTiZB8dFRU5rTo9CAzeycivxV3s+zlTKwrs6WxMxR95n26kwg==", + "dev": true, + "dependencies": { + "escape-string-regexp": "^1.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/style-to-object": { "version": "0.4.4", "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-0.4.4.tgz", @@ -7281,6 +7593,18 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/trim-repeated": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/trim-repeated/-/trim-repeated-1.0.0.tgz", + "integrity": "sha512-pkonvlKk8/ZuR0D5tLW8ljt5I8kmxp2XKymhepUeOdCEfKpZaktSArkLHZt76OB1ZvO9bssUsDty4SWhLvZpLg==", + "dev": true, + "dependencies": { + "escape-string-regexp": "^1.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/trough": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/trough/-/trough-2.1.0.tgz", @@ -7525,6 +7849,15 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true, + "engines": { + "node": ">= 10.0.0" + } + }, "node_modules/update-browserslist-db": { "version": "1.0.13", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz", diff --git a/website/package.json b/website/package.json index d3cd77d7..41384207 100644 --- a/website/package.json +++ b/website/package.json @@ -7,7 +7,8 @@ "start": "astro dev", "build": "astro check && astro build", "preview": "astro preview", - "astro": "astro" + "astro": "astro", + "deploy": "npm run build && npx gh-pages -d dist" }, "dependencies": { "@astrojs/check": "^0.4.1", @@ -15,5 +16,8 @@ "astro": "^4.0.1", "sharp": "^0.32.5", "typescript": "^5.3.3" + }, + "devDependencies": { + "gh-pages": "^6.1.1" } -} \ No newline at end of file +} diff --git a/website/src/content/docs/book/about-the-author.md b/website/src/content/docs/book/about-the-author.md index 5d04c0cf..a396b81c 100644 --- a/website/src/content/docs/book/about-the-author.md +++ b/website/src/content/docs/book/about-the-author.md @@ -10,8 +10,8 @@ Simone Poggiali is an experienced Senior Front-end Developer with a passion for You can reach Simone Poggiali on the following platforms: -* LinkedIn: -* GitHub: -* Twitter: +* LinkedIn: [https://www.linkedin.com/in/simone-poggiali](https://www.linkedin.com/in/simone-poggiali) +* GitHub: [https://github.com/gibbok](https://github.com/gibbok) +* X.com: [https://x.com/gibbok_coding](https://x.com/gibbok_coding) * Email: gibbok.coding📧gmail.com diff --git a/website/src/content/docs/book/class.md b/website/src/content/docs/book/class.md index 3e7a6ceb..3eefad88 100644 --- a/website/src/content/docs/book/class.md +++ b/website/src/content/docs/book/class.md @@ -160,7 +160,7 @@ The `protected` modifier allows access to the class member within the containing The `public` modifier provides unrestricted access to the class member, allowing it to be accessed from anywhere." -### Get & Set +### Get and Set Getters and setters are special methods that allow you to define custom access and modification behavior for class properties. They enable you to encapsulate the internal state of an object and provide additional logic when getting or setting the values of properties. In TypeScript, getters and setters are defined using the `get` and `set` keywords respectively. Here's an example: diff --git a/website/src/content/docs/book/common-built-in-js-objects.md b/website/src/content/docs/book/common-built-in-js-objects.md index 7ff017d0..965ea440 100644 --- a/website/src/content/docs/book/common-built-in-js-objects.md +++ b/website/src/content/docs/book/common-built-in-js-objects.md @@ -7,7 +7,7 @@ sidebar: TypeScript is a superset of JavaScript, it includes all the commonly used built-in JavaScript objects. You can find an extensive list of these objects on the Mozilla Developer Network (MDN) documentation website: - +[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects) Here is a list of some commonly used built-in JavaScript objects: diff --git a/website/src/content/docs/book/downloads-and-website.md b/website/src/content/docs/book/downloads-and-website.md new file mode 100644 index 00000000..f896fee0 --- /dev/null +++ b/website/src/content/docs/book/downloads-and-website.md @@ -0,0 +1,16 @@ +--- +title: Downloads and website +sidebar: + order: 3 + label: 3. Downloads and website +--- + + +You can also download the Epub version: + +[https://github.com/gibbok/typescript-book/tree/main/downloads](https://github.com/gibbok/typescript-book/tree/main/downloads) + +An online version is available at: + +[https://gibbok.github.io/typescript-book](https://gibbok.github.io/typescript-book) + diff --git a/website/src/content/docs/book/downloads.md b/website/src/content/docs/book/downloads.md deleted file mode 100644 index cc22e5dd..00000000 --- a/website/src/content/docs/book/downloads.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Downloads -sidebar: - order: 3 - label: 3. Downloads ---- - - -You can also download the Epub version here: - - - diff --git a/website/src/content/docs/book/exploring-the-type-system.md b/website/src/content/docs/book/exploring-the-type-system.md index a9ff92dd..3616873e 100644 --- a/website/src/content/docs/book/exploring-the-type-system.md +++ b/website/src/content/docs/book/exploring-the-type-system.md @@ -16,7 +16,7 @@ Developers can leverage a dedicated API and create their own custom language ser An example of a real-world custom plugin is "typescript-styled-plugin", which provides syntax error reporting and IntelliSense support for CSS properties in styled components. -For more information and quick start guides, you can refer to the official TypeScript Wiki on GitHub: +For more information and quick start guides, you can refer to the official TypeScript Wiki on GitHub: [https://github.com/microsoft/TypeScript/wiki/](https://github.com/microsoft/TypeScript/wiki/) ### Structural Typing @@ -337,10 +337,10 @@ Here few examples: | T1 \| T2 | T1 ∪ T2 (union) | type XY = 'X' \| 'Y'; | | | | type JK = 1 \| 2; | | | | -| T1 & T2 | T1 ∩ T2 (intersection) | type X = { a: string } | -| | | type Y = { b: string } | +| T1 & T2 | T1 ∩ T2 (intersection) | type X = \{ a: string \} | +| | | type Y = \{ b: string \} | | | | type XY = X & Y | -| | | const x: XY = { a: 'a', b: 'b' } | +| | | const x: XY = \{ a: 'a', b: 'b' \} | | | | | unknown | Universal set | const x: unknown = 1 | @@ -486,7 +486,7 @@ It is worth noting that when using a type assertion, TypeScript will not execute Ambient declarations are files that describe types for JavaScript code, they have a file name format as `.d.ts.`. They are usually imported and used to annotate existing JavaScript libraries or to add types to existing JS files in your project. Many common libraries types can be found at: - +[https://github.com/DefinitelyTyped/DefinitelyTyped/](https://github.com/DefinitelyTyped/DefinitelyTyped/) and can be installed using: @@ -503,6 +503,8 @@ For your defined Ambient Declarations, you can import using the "triple-slash" r You can use Ambient Declarations even within JavaScript files using `// @ts-check`. +The `declare` keyword enables type definitions for existing JavaScript code without importing it, serving as a placeholder for types from another file or globally. + ### Property Checking and Excess Property Checking TypeScript is based on a structural type system but excess property checking is a property of TypeScript which allows it to check whether an object has the exact properties specified in the type. diff --git a/website/src/content/docs/book/getting-started-with-typescript.md b/website/src/content/docs/book/getting-started-with-typescript.md index e93cf0b8..847a0119 100644 --- a/website/src/content/docs/book/getting-started-with-typescript.md +++ b/website/src/content/docs/book/getting-started-with-typescript.md @@ -76,7 +76,7 @@ tsc src/*.ts // Compile any .ts files under the 'src' folder to JavaScript tsc app.ts util.ts --outfile index.js // Compile two TypeScript files (app.ts and util.ts) into a single JavaScript file (index.js) ``` -### TypeScript Configuration File ​​tsconfig.json +### TypeScript Configuration File A tsconfig.json file is used to configure the TypeScript Compiler (tsc). Usually, it is added to the root of the project, together with the `package.json` file. @@ -87,9 +87,9 @@ Notes: At the following link you can find the complete documentation and its schema: - +[https://www.typescriptlang.org/tsconfig](https://www.typescriptlang.org/tsconfig) - +[http://json.schemastore.org/tsconfig](http://json.schemastore.org/tsconfig) The following represents a list of the common and useful configurations: @@ -161,7 +161,7 @@ The first step of this transition is to introduce TypeScript into the build chai The second step is to ensure that your JavaScript tests work alongside TypeScript files so that you can run tests as you convert each module. If you are using Jest, consider using `ts-jest`, which allows you to test TypeScript projects with Jest. -The third step is to include type declarations for third-party libraries in your project. These declarations can be found either bundled or on DefinitelyTyped. You can search for them using and install them using: +The third step is to include type declarations for third-party libraries in your project. These declarations can be found either bundled or on DefinitelyTyped. You can search for them using [https://www.typescriptlang.org/dt/search](https://www.typescriptlang.org/dt/search) and install them using: ```shell npm install --save-dev @types/package-name or yarn add --dev @types/package-name. diff --git a/website/src/content/docs/book/others.md b/website/src/content/docs/book/others.md index cf3eb8a9..e117aca0 100644 --- a/website/src/content/docs/book/others.md +++ b/website/src/content/docs/book/others.md @@ -113,33 +113,33 @@ Promises: Promises are a way to handle asynchronous operations and their results using methods like `.then()` and `.catch()` to handle success and error conditions. -To learn more: +To learn more: [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Async/await: Async/await keywords are a way to provide a more synchronous-looking syntax for working with Promises. The `async` keyword is used to define an asynchronous function, and the `await` keyword is used within an async function to pause execution until a Promise is resolved or rejected. To learn more: - - +[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) +[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) The following API are well supported in TypeScript: Fetch API: - +[https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) Web Workers: - +[https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) Shared Workers: - +[https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker) WebSocket: - +[https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) ### Iterators and Generators -Both Interators and Generators are well supported in TypeScript. +Both Iterators and Generators are well supported in TypeScript. Iterators are objects that implement the iterator protocol, providing a way to access elements of a collection or sequence one by one. It is a structure that contains a pointer to the next element in the iteration. They have a `next()` method that returns the next value in the sequence along with a boolean indicating if the sequence is `done`. @@ -199,7 +199,10 @@ for (const num of generator) { TypeScript also supports async iterators and async Generators. To learn more: - + +[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator) + +[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) ### TsDocs JSDoc Reference @@ -221,11 +224,11 @@ power(10, 2); // function power(base: number, exponent: number): number ``` Full documentation is provided to this link: - +[https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html) From version 3.7 it is possible to generate .d.ts type definitions from JavaScript JSDoc syntax. More information can be found here: - +[https://www.typescriptlang.org/docs/handbook/declaration-files/dts-from-js.html](https://www.typescriptlang.org/docs/handbook/declaration-files/dts-from-js.html) ### @types @@ -237,7 +240,7 @@ npm install --save-dev @types/lodash Will install the type definitions of `lodash` in your current project. -To contribute to the type definitions of @types package, please submit a pull request to . +To contribute to the type definitions of @types package, please submit a pull request to [https://github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped). ### JSX @@ -251,7 +254,7 @@ To use JSX you need to set the `jsx` compiler option in your `tsconfig.json` fil * "react": enables TypeScript's built-in JSX transformation. React.createElement will be used. All options are available here: - +[https://www.typescriptlang.org/tsconfig#jsx](https://www.typescriptlang.org/tsconfig#jsx) ### ES6 Modules @@ -301,7 +304,7 @@ async function* asyncNumbers(): AsyncIterableIterator { })(); ``` -### New.target +### New target meta-property You can use in TypeScript the `new.target` meta-property which enables you to determine if a function or constructor was invoked using the new operator. It allows you to detect whether an object was created as a result of a constructor call. @@ -351,7 +354,7 @@ tsc --watch Starting from TypeScript version 4.9, file monitoring primarily relies on file system events, automatically resorting to polling if an event-based watcher cannot be established. -### Non-null Assertion Operator (Postfix !) +### Non-null Assertion Operator The Non-null Assertion Operator (Postfix !) also called Definite Assignment Assertions is a TypeScript feature that allows you to assert that a variable or property is not null or undefined, even if TypeScript's static type analysis suggests that it might be. With this feature it is possible to remove any explicit checking. @@ -398,7 +401,7 @@ const person: Person = { console.log(person.address?.city); // undefined ``` -### Nullish coalescing operator (??) +### Nullish coalescing operator The nullish coalescing operator `??` returns the right-hand side value if the left-hand side is `null` or `undefined`; otherwise, it returns the left-hand side value. @@ -491,7 +494,7 @@ type NestedArray = [1, [2, [3, 4], 5], 6]; type FlattenedArray = Flatten; // 2 | 3 | 4 | 5 | 1 | 6 ``` -### ECMAScript Module Support in Node.js +### ECMAScript Module Support in Node Node.js added support for ECMAScript Modules starting from version 15.3.0, and TypeScript has had ECMAScript Module Support for Node.js since version 4.7. This support can be enabled by using the `module` property with the value `nodenext` in the tsconfig.json file. Here's an example: @@ -728,7 +731,7 @@ console.log(obj['key-b']); // 456 ### The satisfies Operator -The `satisfies` allows you to check if a given type satisfies a specific interface or condition. In other words, it ensures that a type has all the required properties and methods of a specific interface. It is a way to ensure a variable fits into a definition of a type +The `satisfies` allows you to check if a given type satisfies a specific interface or condition. In other words, it ensures that a type has all the required properties and methods of a specific interface. It is a way to ensure a variable fits into a definition of a type. Here is an example: @@ -929,3 +932,21 @@ Connection closed. ``` The `using` and `await using` declarations are allowed in Statements: `for`, `for-in`, `for-of`, `for-await-of`, `switch`. + +### Import Attributes + +TypeScript 5.3's Import Attributes (labels for imports) tell the runtime how to handle modules (JSON, etc.). This improves security by ensuring clear imports and aligns with Content Security Policy (CSP) for safer resource loading. TypeScript ensures they are valid but lets the runtime handle their interpretation for specific module handling. + +Example: + + +```typescript +import config from './config.json' with { type: 'json' }; +``` + +with dynamic import: + + +```typescript +const config = import('./config.json', { with: { type: 'json' } }); +``` diff --git a/website/src/content/docs/book/table-of-contents.md b/website/src/content/docs/book/table-of-contents.md index 4b8c218f..430d8594 100644 --- a/website/src/content/docs/book/table-of-contents.md +++ b/website/src/content/docs/book/table-of-contents.md @@ -9,7 +9,7 @@ sidebar: - The Concise TypeScript Book - Translations - - Downloads + - Downloads and website - Table of Contents - Introduction - About the Author @@ -22,7 +22,7 @@ sidebar: - Getting Started With TypeScript - Installation - Configuration - - TypeScript Configuration File ​​tsconfig.json + - TypeScript Configuration File - target - lib - strict @@ -132,7 +132,7 @@ sidebar: - Constructor - Private and Protected Constructors - Access Modifiers - - Get \& Set + - Get and Set - Auto-Accessors in Classes - this - Parameter Properties @@ -182,6 +182,7 @@ sidebar: - Lowercase\ - Capitalize\ - Uncapitalize\ + - NoInfer\ - Others - Errors and Exception Handling - Mixin classes @@ -193,18 +194,18 @@ sidebar: - ES6 Modules - ES7 Exponentiation Operator - The for-await-of Statement - - New.target + - New target meta-property - Dynamic Import Expressions - "tsc –watch" - - Non-null Assertion Operator (Postfix !) + - Non-null Assertion Operator - Defaulted declarations - Optional Chaining - - Nullish coalescing operator (??) + - Nullish coalescing operator - Template Literal Types - Function overloading - Recursive Types - Recursive Conditional Types - - ECMAScript Module Support in Node.js + - ECMAScript Module Support in Node - Assertion Functions - Variadic Tuple Types - Boxed types @@ -215,4 +216,6 @@ sidebar: - Type-Only Imports and Export - using declaration and Explicit Resource Management - await using declaration + - Import Attributes + diff --git a/website/src/content/docs/book/translations.md b/website/src/content/docs/book/translations.md index 50822e83..5a8aff64 100644 --- a/website/src/content/docs/book/translations.md +++ b/website/src/content/docs/book/translations.md @@ -8,5 +8,5 @@ sidebar: This book has been translated into several language versions, including: -* [Chinese](./README-zh_CN.md) +[Chinese](https://github.com/gibbok/typescript-book/blob/main/README-zh_CN.md) diff --git a/website/src/content/docs/book/type-from-value.md b/website/src/content/docs/book/type-from-value.md index 14331090..3d9d9a07 100644 --- a/website/src/content/docs/book/type-from-value.md +++ b/website/src/content/docs/book/type-from-value.md @@ -9,6 +9,6 @@ sidebar: Type from Value in TypeScript refers to the automatic inference of a type from a value or expression through type inference. ```typescript -const x = 'x'; // TypeScript can automatically infer that the type of the message variable is string +const x = 'x'; // TypeScript infers 'x' as a string literal with 'const' (immutable), but widens it to 'string' with 'let' (reassignable). ``` diff --git a/website/src/content/docs/book/type-manipulation.md b/website/src/content/docs/book/type-manipulation.md index 846436cb..1fe6a989 100644 --- a/website/src/content/docs/book/type-manipulation.md +++ b/website/src/content/docs/book/type-manipulation.md @@ -80,7 +80,7 @@ Several built-in utility types can be used to manipulate types, below a list of #### Awaited\ -Constructs a type recursively unwrap Promises. +Constructs a type that recursively unwraps Promise types. ```typescript type A = Awaited>; // string @@ -333,3 +333,29 @@ Uncapitalize the name of the input type T. type MyType = Uncapitalize<'Abc'>; // "abc" ``` +#### NoInfer\ + +NoInfer is a utility type designed to block the automatic inference of types within the scope of a generic function. + +Example: + +```typescript +// Automatic inference of types within the scope of a generic function. +function fn(x: T[], y: T) { + return x.concat(y); +} +const r = fn(['a', 'b'], 'c'); // Type here is ("a" | "b" | "c")[] +``` + +With NoInfer: + + +```typescript +// Example function that uses NoInfer to prevent type inference +function fn2(x: T[], y: NoInfer) { + return x.concat(y); +} + +const r2 = fn2(['a', 'b'], 'c'); // Error: Type Argument of type '"c"' is not assignable to parameter of type '"a" | "b"'. +``` + diff --git a/website/src/content/docs/book/typescript-introduction.md b/website/src/content/docs/book/typescript-introduction.md index 813944da..88555d21 100644 --- a/website/src/content/docs/book/typescript-introduction.md +++ b/website/src/content/docs/book/typescript-introduction.md @@ -10,7 +10,7 @@ sidebar: TypeScript is a strongly typed programming language that builds on JavaScript. It was originally designed by Anders Hejlsberg in 2012 and is currently developed and maintained by Microsoft as an open source project. -TypeScript compiles to JavaScript and can be executed in any JavaScript engine (e.g., a browser or server Node.js). +TypeScript compiles to JavaScript and can be executed in any JavaScript runtime (e.g., a browser or server Node.js). TypeScript supports multiple programming paradigms such as functional, generic, imperative, and object-oriented. TypeScript is neither an interpreted nor a compiled language. @@ -43,7 +43,7 @@ For instance, consider a function in a JavaScript file with the `.js` extension, const sum = (a, b) => a + b; ``` -The function can be converted and used in TypeScript by changing the file extension to `.ts`. However, if the same function is annotated with TypeScript types, it cannot be executed in any JavaScript engine without compilation. The following TypeScript code will produce a syntax error if it is not compiled: +The function can be converted and used in TypeScript by changing the file extension to `.ts`. However, if the same function is annotated with TypeScript types, it cannot be executed in any JavaScript runtime without compilation. The following TypeScript code will produce a syntax error if it is not compiled: ```typescript @@ -87,7 +87,7 @@ This error occurs because TypeScript strictly enforces type compatibility, and i ### TypeScript Code Generation -The TypeScript compiler has two main responsibilities: checking for type errors and compiling to JavaScript. These two processes are independent of each other. Types do not affect the execution of the code in a JavaScript engine, as they are completely erased during compilation. TypeScript can still output JavaScript even in the presence of type errors. +The TypeScript compiler has two main responsibilities: checking for type errors and compiling to JavaScript. These two processes are independent of each other. Types do not affect the execution of the code in a JavaScript runtime, as they are completely erased during compilation. TypeScript can still output JavaScript even in the presence of type errors. Here is an example of TypeScript code with a type error: diff --git a/website/src/content/docs/index.mdx b/website/src/content/docs/index.mdx index a20e1792..4eea0a50 100644 --- a/website/src/content/docs/index.mdx +++ b/website/src/content/docs/index.mdx @@ -6,7 +6,7 @@ hero: tagline: The Concise TypeScript Book provides a comprehensive and succinct overview of TypeScript's capabilities. It offers clear explanations covering all aspects found in the latest version of the language, from its powerful type system to advanced features. Whether you're a beginner or an experienced developer, this book is an invaluable resource to enhance your understanding and proficiency in TypeScript.

This book is completely Free and Open Source. actions: - text: Read now! - link: /book/the-concise-typescript-book/ + link: /typescript-book/book/the-concise-typescript-book/ icon: right-arrow variant: primary - text: GitHub diff --git a/website/src/content/docs/zh-cn/book/about-the-author.md b/website/src/content/docs/zh-cn/book/about-the-author.md index 42277043..7c3e0ffc 100644 --- a/website/src/content/docs/zh-cn/book/about-the-author.md +++ b/website/src/content/docs/zh-cn/book/about-the-author.md @@ -10,8 +10,8 @@ Simone Poggiali 是一位经验丰富的高级前端开发人员,自 90 年代 您可以通过以下平台联系 Simone Poggiali: -* 领英: -* GitHub: -* 推特: +* 领英: [https://www.linkedin.com/in/simone-poggiali](https://www.linkedin.com/in/simone-poggiali) +* GitHub: [https://github.com/gibbok](https://github.com/gibbok) +* X.com: [https://x.com/gibbok_coding](https://x.com/gibbok_coding) * 电子邮箱: gibbok.coding📧gmail.com diff --git a/website/src/content/docs/zh-cn/book/common-built-in-js-objects.md b/website/src/content/docs/zh-cn/book/common-built-in-js-objects.md index 7ad155e8..fddb295d 100644 --- a/website/src/content/docs/zh-cn/book/common-built-in-js-objects.md +++ b/website/src/content/docs/zh-cn/book/common-built-in-js-objects.md @@ -7,7 +7,7 @@ sidebar: TypeScript 是 JavaScript 的超集,它包含所有常用的内置 JavaScript 对象。您可以在 Mozilla 开发者网络 (MDN) 文档网站上找到这些对象的详细列表: - +[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects) 以下是一些常用的内置 JavaScript 对象的列表: diff --git a/website/src/content/docs/zh-cn/book/downloads-and-website.md b/website/src/content/docs/zh-cn/book/downloads-and-website.md new file mode 100644 index 00000000..6d2ea0fd --- /dev/null +++ b/website/src/content/docs/zh-cn/book/downloads-and-website.md @@ -0,0 +1,16 @@ +--- +title: 下载和网站 +sidebar: + order: 3 + label: 3. 下载和网站 +--- + + +您还可以下载 Epub 版本: + +[https://github.com/gibbok/typescript-book/tree/main/downloads](https://github.com/gibbok/typescript-book/tree/main/downloads) + +在线版本可在以下位置获得: + +[https://gibbok.github.io/typescript-book](https://gibbok.github.io/typescript-book) + diff --git a/website/src/content/docs/zh-cn/book/downloads.md b/website/src/content/docs/zh-cn/book/downloads.md deleted file mode 100644 index 45bf16f6..00000000 --- a/website/src/content/docs/zh-cn/book/downloads.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: 下载 -sidebar: - order: 3 - label: 3. 下载 ---- - - -您还可以在这里下载 Epub 版本: - - - diff --git a/website/src/content/docs/zh-cn/book/exploring-the-type-system.md b/website/src/content/docs/zh-cn/book/exploring-the-type-system.md index 09ffdb98..28ba86e3 100644 --- a/website/src/content/docs/zh-cn/book/exploring-the-type-system.md +++ b/website/src/content/docs/zh-cn/book/exploring-the-type-system.md @@ -16,7 +16,7 @@ TypeScript 的语言服务, 也被称为 tsserver,提供了各种功能,例 现实世界中的自定义插件的一个示例是"typescript-styled-plugin",它为样式组件中的 CSS 属性提供语法错误报告和 IntelliSense 支持。 -有关更多信息和快速入门指南,您可以参考 GitHub 上的官方 TypeScript Wiki: +有关更多信息和快速入门指南,您可以参考 GitHub 上的官方 TypeScript Wiki: [https://github.com/microsoft/TypeScript/wiki/](https://github.com/microsoft/TypeScript/wiki/) ### 结构类型 @@ -336,10 +336,10 @@ TypeScript 支持各种类型的集合: | T1 \| T2 | T1 ∪ T2 (并集) | type XY = 'X' \| 'Y'; | | | | type JK = 1 \| 2; | | | | -| T1 & T2 | T1 ∩ T2 (交集) | type X = { a: string } | -| | | type Y = { b: string } | +| T1 & T2 | T1 ∩ T2 (交集) | type X = \{ a: string \} | +| | | type Y = \{ b: string \} | | | | type XY = X & Y | -| | | const x: XY = { a: 'a', b: 'b' } | +| | | const x: XY = \{ a: 'a', b: 'b' \} | | | | | unknown | 通用集 | const x: unknown = 1 | @@ -491,7 +491,7 @@ let y = x!; // number 环境声明是描述 JavaScript 代码类型的文件,它们的文件名格式为.d.ts.. 它们通常被导入并用于注释现有的 JavaScript 库或向项目中的现有 JS 文件添加类型。 许多常见的库类型可以在以下位置找到: - +[https://github.com/DefinitelyTyped/DefinitelyTyped/](https://github.com/DefinitelyTyped/DefinitelyTyped/) ```shell npm install --save-dev @types/library-name @@ -506,6 +506,8 @@ npm install --save-dev @types/library-name 即使在 JavaScript 文件中,您也可以通过 `// @ts-check` 使用环境声明。 +`declare` 关键字可以为现有的 JavaScript 代码启用类型定义,而无需导入它,作为来自另一个文件或全局的类型的占位符。 + ### 属性检测和多余属性检测 TypeScript 基于结构类型系统,但过多的属性检查是 TypeScript 的一个属性,它允许它检查对象是否具有类型中指定的确切属性。 @@ -662,7 +664,7 @@ TypeScript 提供了控制加宽过程的方法,例如使用"const"。 For example: ```typescript -const x = 'x'; // TypeScript 将 x 的类型推断为 'x',一种较窄的类型 +const x = 'x'; // TypeScript 将 'x' 推断为带有 'const'(不可变)的字符串字面量,但将其扩展为带有 'let'(可重新赋值)的 'string'。 let y: 'y' | 'x' = 'y'; y = x; // 有效: x的类型推断为 'x' ``` diff --git a/website/src/content/docs/zh-cn/book/extending-types.md b/website/src/content/docs/zh-cn/book/extending-types.md index 4056456d..040950d0 100644 --- a/website/src/content/docs/zh-cn/book/extending-types.md +++ b/website/src/content/docs/zh-cn/book/extending-types.md @@ -54,4 +54,3 @@ interface B extends A { } ``` - diff --git a/website/src/content/docs/zh-cn/book/getting-started-with-typescript.md b/website/src/content/docs/zh-cn/book/getting-started-with-typescript.md index 05014056..31b846b8 100644 --- a/website/src/content/docs/zh-cn/book/getting-started-with-typescript.md +++ b/website/src/content/docs/zh-cn/book/getting-started-with-typescript.md @@ -76,7 +76,7 @@ tsc src/*.ts // 将 'src' 文件夹下任意的 .ts 文件编译成 JavaScript tsc app.ts util.ts --outfile index.js // 将 2 个 TypeScript 文件 (app.ts 和 util.ts) 编译成 1 个 JavaScript 文件 (index.js) ``` -### TypeScript 的配置文件 tsconfig.json +### TypeScript 的配置文件 tsconfig.json 文件用于配置 TypeScript 编译器 (tsc)。通常,它与文件一起添加到项目的根目录中package.json。 @@ -87,9 +87,9 @@ tsconfig.json 文件用于配置 TypeScript 编译器 (tsc)。通常,它与文 在以下链接中,您可以找到完整的文档及其配置示例: - +[https://www.typescriptlang.org/tsconfig](https://www.typescriptlang.org/tsconfig) - +[http://json.schemastore.org/tsconfig](http://json.schemastore.org/tsconfig) 以下列出了常见且有用的配置: @@ -143,6 +143,7 @@ TypeScript 可以为各种模块系统生成代码,包括 UMD、System、ESNex "include"属性向编译器指示我们想要包含的文件列表。此属性允许类似 glob 的模式,例如 "\*_" 表示任何子目录,"_" 表示任何文件名,"?" 表示可选字符。 + #### exclude "exclude"属性向编译器指示不应包含在编译中的文件列表。这可以包括"node_modules"等文件或测试文件 @@ -160,7 +161,7 @@ TypeScript 在为某些高级或低级 JavaScript 功能生成代码时使用帮 第二步是确保您的 JavaScript 测试与 TypeScript 文件一起工作,以便您可以在转换每个模块时运行测试。如果您正在使用 Jest,请考虑使用ts-jest,它允许您使用 Jest 测试 TypeScript 项目。 -第三步是在项目中包含第三方库的类型声明。 这些声明可以第三方库的类型声明文件或专门的声明包中找到,你能通过 搜索并安装它们。: +第三步是在项目中包含第三方库的类型声明。 这些声明可以第三方库的类型声明文件或专门的声明包中找到,你能通过 [https://www.typescriptlang.org/dt/search](https://www.typescriptlang.org/dt/search) 搜索并安装它们。: ```shell npm install --save-dev @types/package-name or yarn add --dev @types/package-name. diff --git a/website/src/content/docs/zh-cn/book/literal-inference.md b/website/src/content/docs/zh-cn/book/literal-inference.md index a032cb82..7b183c8d 100644 --- a/website/src/content/docs/zh-cn/book/literal-inference.md +++ b/website/src/content/docs/zh-cn/book/literal-inference.md @@ -50,4 +50,3 @@ let o = { }; ``` - diff --git a/website/src/content/docs/zh-cn/book/others.md b/website/src/content/docs/zh-cn/book/others.md index 85a5090f..1d2b21dd 100644 --- a/website/src/content/docs/zh-cn/book/others.md +++ b/website/src/content/docs/zh-cn/book/others.md @@ -113,33 +113,33 @@ Promises: Promise 是一种处理异步操作及其结果的方法,使用 `.then()`和等方法 `.catch()` 来处理成功和错误条件。 -要了解更多信息: +要了解更多信息: [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Async/await: Async/await 关键字是一种为处理 Promise 提供看起来更同步的语法的方法。`async` 关键字用于定义异步函数,并且 `await` 关键字在异步函数中使用以暂停执行,直到 Promise 被解决或拒绝。 要了解更多信息: - - +[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) +[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) TypeScript 很好地支持以下 API: Fetch API: - +[https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) Web Workers: - +[https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) Shared Workers: - +[https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker) WebSocket: - +[https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) ### 迭代器和生成器 -TypeScript 很好地支持交互器和生成器。 +TypeScript 对迭代器和生成器都提供了很好的支持。 迭代器是实现迭代器协议的对象,提供了一种逐个访问集合或序列元素的方法。它是一个包含指向迭代中下一个元素的指针的结构。他们有一个 `next()` 方法返回序列中的下一个值以及指示序列是否为 的布尔值 `done` 。 @@ -200,9 +200,9 @@ TypeScript 还支持异步迭代器和异步生成器。 要了解更多信息: - +[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator) - +[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) ### TsDocs JSDoc 参考 @@ -224,10 +224,10 @@ power(10, 2); // function power(base: number, exponent: number): number ``` 此链接提供了完整文档: - +[https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html) 从版本 3.7 开始,可以从 JavaScript JSDoc 语法生成 .d.ts 类型定义。更多信息可以在这里找到: - +[https://www.typescriptlang.org/docs/handbook/declaration-files/dts-from-js.html](https://www.typescriptlang.org/docs/handbook/declaration-files/dts-from-js.html) ### @types @@ -239,7 +239,7 @@ npm install --save-dev @types/lodash 将在您当前的项目中安装 `lodash` 的类型定义。 -要为 @types 包的类型定义做出贡献,请向 提交pr请求。 +要为 @types 包的类型定义做出贡献,请向 [https://github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) 提交pr请求。 ### JSX @@ -253,7 +253,7 @@ TypeScript 通过提供类型检查和静态分析来扩展 JSX 的功能。 * "react": 启用 TypeScript 的内置 JSX 转换。 将使用 React.createElement 。 所有选项均可在此处使用: - +[https://www.typescriptlang.org/tsconfig#jsx](https://www.typescriptlang.org/tsconfig#jsx) ### ES6 模块 @@ -302,7 +302,7 @@ async function* asyncNumbers(): AsyncIterableIterator { })(); ``` -### New.target +### New target 元属性 您可以在 TypeScript 中使用 `new.target` 元属性,该属性使您能够确定是否使用 new 运算符调用函数或构造函数。它允许您检测对象是否是由于构造函数调用而创建的。 @@ -385,7 +385,7 @@ const person: Person = { console.log(person.address?.city); // undefined ``` -### 空合并运算符 (??) +### 空合并运算符 如果 `??` 左侧是 `null` 或者 `undefined` ,则空合并运算符返回右侧值,否则,它返回左侧值。 @@ -476,7 +476,7 @@ type NestedArray = [1, [2, [3, 4], 5], 6]; type FlattenedArray = Flatten; // 2 | 3 | 4 | 5 | 1 | 6 ``` -### Node.js 中的 ECMAScript 模块支持 +### Node 中的 ECMAScript 模块支持 Node.js 从 15.3.0 版本开始添加了对 ECMAScript 模块的支持,而 TypeScript 从 4.7 版本开始增加了对 Node.js 的 ECMAScript 模块支持。可以通过将 `tsconfig.json` 文件中的`module`属性的值设置为 `nodenext` 来启用此支持。这是一个例子: @@ -914,3 +914,21 @@ Connection closed. ``` 语句中允许使用"using"和"await using"声明:"for"、"for-in"、"for-of"、"for-await-of"、"switch"。 + +### 导入属性 + +TypeScript 5.3 的导入属性(导入标签)告诉运行时如何处理模块(JSON 等)。这通过确保干净的导入来提高安全性,并与内容安全策略 (CSP) 保持一致,以实现更安全的资源加载。TypeScript 确保它们有效,但让运行时处理它们的解释以进行特定的模块处理。 + +示例: + + +```typescript +import config from './config.json' with { type: 'json' }; +``` + +使用动态导入: + + +```typescript +const config = import("./config.json", { with: { type: "json" } }) +``` diff --git a/website/src/content/docs/zh-cn/book/table-of-contents.md b/website/src/content/docs/zh-cn/book/table-of-contents.md index 68efba99..3372f605 100644 --- a/website/src/content/docs/zh-cn/book/table-of-contents.md +++ b/website/src/content/docs/zh-cn/book/table-of-contents.md @@ -9,7 +9,7 @@ sidebar: - 简洁的TypeScript之书 - 翻译 - - 下载 + - 下载和网站 - 目录表 - 介绍 - 关于作者 @@ -22,7 +22,7 @@ sidebar: - TypeScript 入门 - 安装 - 配置 - - TypeScript 的配置文件 tsconfig.json + - TypeScript 的配置文件 - target - lib - strict @@ -183,6 +183,7 @@ sidebar: - Lowercase\ - Capitalize\ - Uncapitalize\ + - NoInfer\ - 其他 - 错误和异常处理 - 混合类 @@ -194,17 +195,17 @@ sidebar: - ES6 模块 - ES7 求幂运算符 - for-await-of 语句 - - New.target + - New target 元属性 - 动态导入表达式 - "tsc –watch" - 默认声明 - 可选链 - - 空合并运算符 (??) + - 空合并运算符 - 模板字符串类型 - 函数重载 - 递归类型 - 递归条件类型 - - Node.js 中的 ECMAScript 模块支持 + - Node 中的 ECMAScript 模块支持 - 断言函数 - 可变参数元组类型 - 装箱类型 @@ -215,5 +216,6 @@ sidebar: - 仅类型导入和导出 - 使用声明和显式资源管理 - 使用声明等待 + - 导入属性 diff --git a/website/src/content/docs/zh-cn/book/the-concise-typescript-book.md b/website/src/content/docs/zh-cn/book/the-concise-typescript-book.md index ba89de15..44eb9fdf 100644 --- a/website/src/content/docs/zh-cn/book/the-concise-typescript-book.md +++ b/website/src/content/docs/zh-cn/book/the-concise-typescript-book.md @@ -10,3 +10,7 @@ sidebar: 本书完全免费且开源。 +如果您发现这本 TypeScript 书籍很有价值并希望做出贡献,请考虑通过 PayPal 支持我的努力。谢谢! + +[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/donate/?business=QW82ZS956XLFY&no_recurring=0¤cy_code=EUR) + diff --git a/website/src/content/docs/zh-cn/book/translations.md b/website/src/content/docs/zh-cn/book/translations.md index ff6cc900..16dbb0d0 100644 --- a/website/src/content/docs/zh-cn/book/translations.md +++ b/website/src/content/docs/zh-cn/book/translations.md @@ -8,5 +8,5 @@ sidebar: 本书已被翻译成多种语言版本,包括: -* [中文](./README-zh_CN.md) +[中文](https://github.com/gibbok/typescript-book/blob/main/README-zh_CN.md) diff --git a/website/src/content/docs/zh-cn/book/type-manipulation.md b/website/src/content/docs/zh-cn/book/type-manipulation.md index 405c4b64..4fe4fffa 100644 --- a/website/src/content/docs/zh-cn/book/type-manipulation.md +++ b/website/src/content/docs/zh-cn/book/type-manipulation.md @@ -80,7 +80,7 @@ type MyType = MyTuple[2]; // boolean #### Awaited\ -构造一个递归解包 Promise 的类型。 +构造一个递归解包 Promise 类型的类型。 ```typescript type A = Awaited>; // string @@ -333,3 +333,29 @@ type MyType = Capitalize<'abc'>; // "Abc" type MyType = Uncapitalize<'Abc'>; // "abc" ``` +#### NoInfer\ + +NoInfer 是一种实用类型,旨在阻止泛型函数范围内类型的自动推断。 + +示例: + +```typescript +// 泛型函数范围内类型的自动推断。 +function fn(x: T[], y: T) { + return x.concat(y); +} +const r = fn(['a', 'b'], 'c'); // 此处的类型为 ("a" | "b" | "c")[] +``` + +使用 NoInfer: + + +```typescript +// 使用 NoInfer 阻止类型推断的示例函数 +function fn2(x: T[], y: NoInfer) { + return x.concat(y); +} + +const r2 = fn2(["a", "b"], "c"); // 错误:类型为“c”的类型参数不能分配给类型为“a”|“b”的参数。 +``` + diff --git a/website/src/content/docs/zh-cn/book/typescript-introduction.md b/website/src/content/docs/zh-cn/book/typescript-introduction.md index b2019797..eaf95ba9 100644 --- a/website/src/content/docs/zh-cn/book/typescript-introduction.md +++ b/website/src/content/docs/zh-cn/book/typescript-introduction.md @@ -10,7 +10,7 @@ sidebar: TypeScript 是一种基于 JavaScript 构建的强类型编程语言。它最初由 Anders Hejlsberg 于 2012 年设计,目前由 Microsoft 作为开源项目开发和维护。 -TypeScript 编译为 JavaScript,并且可以在任何 JavaScript 引擎(例如浏览器或服务器 Node.js)中执行。 +TypeScript 编译为 JavaScript,并且可以在任何 JavaScript 运行时(例如浏览器或服务器 Node.js)中执行。 TypeScript 支持多种编程范式,例如函数式、泛型、命令式和面向对象。TypeScript 既不是解释型语言,也不是编译型语言。 @@ -42,7 +42,7 @@ TypeScript是用`.ts`或`.tsx`文件编写的, 而JavaScript是用`.js`或`.jsx` const sum = (a, b) => a + b; ``` -该函数可以通过将文件扩展名更改为 .TypeScript 来转换和使用.ts。但是,如果同一个函数使用 TypeScript 类型进行注释,则未经编译就无法在任何 JavaScript 引擎中执行。如果未编译以下 TypeScript 代码,将会产生语法错误 +该函数可以通过将文件扩展名更改为 .TypeScript 来转换和使用.ts。但是,如果同一个函数使用 TypeScript 类型进行注释,则未经编译就无法在任何 JavaScript 运行时中执行。如果未编译以下 TypeScript 代码,将会产生语法错误 ```typescript @@ -86,7 +86,7 @@ const result = 1 + true; // 在JavaScript中, 结果等于2 ### TypeScript 代码生成 -TypeScript 编译器有两个主要职责:检查类型错误和编译为 JavaScript。这两个过程是相互独立的。类型不会影响 JavaScript 引擎中代码的执行,因为它们在编译过程中会被完全擦除。即使存在类型错误,TypeScript 仍然可以输出 JavaScript。以下是存在类型错误的 TypeScript 代码示例: +TypeScript 编译器有两个主要职责:检查类型错误和编译为 JavaScript。这两个过程是相互独立的。类型不会影响 JavaScript 运行时中代码的执行,因为它们在编译过程中会被完全擦除。即使存在类型错误,TypeScript 仍然可以输出 JavaScript。以下是存在类型错误的 TypeScript 代码示例: ```typescript diff --git a/website/src/content/docs/zh-cn/index.mdx b/website/src/content/docs/zh-cn/index.mdx index 6ee31b9f..45f5fb5d 100644 --- a/website/src/content/docs/zh-cn/index.mdx +++ b/website/src/content/docs/zh-cn/index.mdx @@ -8,7 +8,7 @@ hero: TypeScript 的理解和熟练程度的宝贵资源。

本书完全免费且开源。 actions: - text: 现在读! - link: /zh-cn/book/the-concise-typescript-book/ + link: /typescript-book/zh-cn/book/the-concise-typescript-book/ icon: right-arrow variant: primary - text: GitHub