├── .editorconfig ├── .gitignore ├── .prettierrc ├── .vscode └── settings.json ├── LICENSE ├── README-en.md ├── README.md ├── assets ├── inlay-hint.jpg └── overview.png ├── babel.config.js ├── package.json ├── pnpm-lock.yaml ├── src ├── entry │ ├── main.spec.ts │ └── main.ts └── modules │ ├── compiler.ts │ ├── helpers │ ├── helpers.enum.ts │ └── helpers.ts │ ├── playground │ ├── effect-hkt.ts │ ├── hkt.ts │ ├── hkts.ts │ └── samples.ts │ ├── transformer │ ├── transformer-plugin.spec.ts │ └── transformer-plugin.ts │ ├── types │ └── ast.d.ts │ ├── utils │ ├── formatter.spec.ts │ ├── formatter.ts │ ├── general.ts │ ├── generator.spec.ts │ ├── generator.ts │ ├── parsing.spec.ts │ ├── parsing.ts │ ├── typing.spec.ts │ └── typing.ts │ └── vm │ ├── eval.d.ts │ ├── syntax │ ├── env.d.ts │ ├── loop.d.ts │ └── syntax.d.ts │ └── utils │ ├── helper.d.ts │ └── nat.d.ts └── tsconfig.json /.editorconfig: -------------------------------------------------------------------------------- 1 | # Stop the editor from looking for .editorconfig files in the parent directories 2 | # root = true 3 | 4 | [*] 5 | # Non-configurable Prettier behaviors 6 | charset = utf-8 7 | insert_final_newline = true 8 | # Caveat: Prettier won’t trim trailing whitespace inside template strings, but your editor might. 9 | # trim_trailing_whitespace = true 10 | 11 | # Configurable Prettier behaviors 12 | # (change these if your Prettier config differs) 13 | end_of_line = lf 14 | indent_style = space 15 | indent_size = 2 16 | max_line_length = 80 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "tabWidth": 2, 3 | "useTabs": false, 4 | "trailingComma": "all", 5 | "semi": true, 6 | "singleQuote": true 7 | } 8 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "typescript.tsdk": "node_modules/typescript/lib", 3 | "[markdown]": { 4 | "editor.unicodeHighlight.ambiguousCharacters": false, 5 | "editor.unicodeHighlight.invisibleCharacters": false, 6 | "diffEditor.ignoreTrimWhitespace": false, 7 | "editor.wordWrap": "on", 8 | "editor.quickSuggestions": { 9 | "comments": "off", 10 | "strings": "on", 11 | "other": "on" 12 | }, 13 | "cSpell.fixSpellingWithRenameProvider": true, 14 | "cSpell.advanced.feature.useReferenceProviderWithRename": true, 15 | "cSpell.advanced.feature.useReferenceProviderRemove": "/^#+\\s/", 16 | "editor.defaultFormatter": "esbenp.prettier-vscode", 17 | "editor.formatOnSave": true 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Sg 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README-en.md: -------------------------------------------------------------------------------- 1 | # Understanding TypeScript Type-level Programming 2 | 3 | [中文](./README.md) 4 | 5 | An experimental transpiler that makes simple TypeScript computations happen in type-level, purely in its type system. 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 理解 TypeScript 类型编程 2 | 3 | ## 简介 4 | 5 | 文本试图说明: 6 | 7 | 1. 值编程和类型编程在本质上没有什么区别,TypeScript 的类型编程仅仅是在 TypeScript 类型空间中的编程。通过建立 TypeScript 类型编程和值编程的对应关系,开发者可以很容易地掌握 TypeScript 类型编程。 8 | 2. JavaScript 的函数在类型编程中对应泛型类型。高阶函数则对应高阶类型。TypeScript 类型系统本身不支持高阶类型,通过编码可以在某种程度上实现高阶类型。在理论上,我们可以通过设计一个翻译器来实现 JavaScript 上的运行时计算过程到 TypeScript 类型编译期计算过程的翻译。 9 | 3. 通过对 TypeScript 类型编程的研究,和适当的类型编程实践,开发者可以更好地掌握 TypeScript 这门语言,实现对业务的精准建模,写出更好的代码。 10 | 11 | ## 类型编程的基本概念 12 | 13 | 首先,我们需要定义清楚什么是类型编程。 14 | 15 | ### TypeScript 的值空间和类型空间 16 | 17 | 为了定义什么是类型编程,我们需要引入一对概念:值空间和类型空间。 18 | 19 | TypeScript 不仅为 JavaScript 引入了一些新的语法和特性,最重要的是附加了一个静态的、强的类型系统,让 JavaScript 代码库也能够得到类型检查和现代化的语言服务。 20 | TypeScript 的编译器`tsc`在编译代码时,会对代码进行类型检查,擦除 TypeScript 源码上的类型信息并将新语法和特性转译为可被 JavaScript 解释器执行的 JavaScript 代码。 21 | 22 | 一份典型的 TypeScript 代码,由在编译期和运行时这两个不同时期执行的子语言交织而成。这两个语言分别负责 TypeScript 这门语言的静态语义和动态语义。 23 | 24 | 1. 类型语言。它包括 JavaScript 中不存在的语法成分:如,类型别名关键字`type`和取类型操作符`typeof`,泛型的实例化记号`<>`,`:`和`enum`等。 25 | 1. 它在编译期通过类型检查器的类型检查被执行,执行规则由类型检查器所隐式表示的定型规则定义。承担了 TypeScript 的静态语义。 26 | 2. JavaScript,姑且称之为值语言。它在运行时被 JavaScript 运行环境执行,承担了 TypeScript 的动态语义。 27 | 28 | 如下面这份代码中,类型定义`type States = Array;`和类型标注`: States`就是类型语言中的成分,不是合法的 JavaScript 成分,在 JavaScript 中并不存在; 29 | 而`concat([1], [2])`则是 JavaScript 中的成分,不是合法的类型语言中的成分。 30 | 31 | ```ts 32 | enum State { 33 | Todo, 34 | Finished, 35 | } 36 | type States = Array; 37 | function mergeStates(a: States, b: States): States { 38 | return [...a, ...b]; 39 | } 40 | const result = mergeStates([State.Todo], [State.Finished]); 41 | type Result = typeof result; 42 | ``` 43 | 44 | 其 JavaScript 的部分为: 45 | 46 | ```js 47 | const State = { 48 | Todo: 0, 49 | Finished: 1, 50 | 0: 'Todo', 51 | 1: 'Finished', 52 | }; 53 | function mergeStates(a, b) { 54 | return [...a, ...b]; 55 | } 56 | const result = mergeStates([State.Todo], [State.Finished]); 57 | ``` 58 | 59 | 其类型语言的部分: 60 | 61 | ```ts 62 | enum State { 63 | Todo, 64 | Finished, 65 | } 66 | type States = Array; 67 | declare function mergeStates(a: States, b: States): States; 68 | declare const result: States; 69 | type Result = typeof result; 70 | ``` 71 | 72 | 这两个子语言可以各自独立存在,独立执行。这自然地将 TypeScript 分为了值空间和类型空间。当我们考虑 TypeScript 中的一个项时,它可能仅属于值空间,也可能仅属于类型空间,又或是同时属于类型空间和值空间。例如: 73 | 74 | 1. 常量`result`是值,仅属于值空间。 75 | 1. 类型`States`是类型,仅属于类型空间。 76 | 1. 作为类构造器的`Array`,它既是值空间中的函数、类构造器,又是类型语言中的一个泛型类型; 77 | 1. 作为枚举`enum`的`State`,它既是值空间中的一个 Object,又是类型语言中的一个枚举类型。 78 | 79 | 值空间中的项可以单向地转换为类型空间中的项,例如: 80 | 81 | 1. 通过类型语言中的`typeof`运算符,我们可以获取一个值空间中的符号的类型,得到的类型仅存在于值空间。在 TypeScript 中,仅存在于类型空间的项无法对值空间产生影响。 82 | 83 | ![Overview](./assets/overview.png) 84 | 85 | ### 类型编程 86 | 87 | 类型编程 (Type-level Programming)就是用编程的方式,操作类型空间中的类型。而值编程(Value-level Programming, 即一般的编程),操作的是值空间中的值。 88 | 89 | 类型编程在函数式编程语言社区由来已久,人们对 Haskell 和 Scala 的类型编程就有深入的研究,因为它们有着较强的静态类型系统。早在 2006 年,一个 Haskell Wiki 的页面中[^OOP-vs-type-classes],就已经在使用 Type Gymnastics(类型体操)来指代那些复杂烧脑的类型操作。下面列举了这些社区中一些常见的类型编程主题: 90 | 91 | [^OOP-vs-type-classes]: https://wiki.haskell.org/OOP_vs_type_classes 92 | 93 | 1. Church 编码 [^thinking-with-types] [^type-level-programming-in-scala] 94 | 1. Peano 数所构建的自然数类型,及其上的递归函数和算术 [^thinking-with-types] [^type-level-programming-in-scala] 95 | 1. 井字棋(Tic-Tac-Toe) [^type-level-programming-in-scala] 96 | 1. 存在类型(Existential Types)[^thinking-with-types] 97 | 1. 高阶类型(Higher-kinded Types) [^thinking-with-types] 98 | 1. 广义代数数据类型(GADTs) [^thinking-with-types] 99 | 1. 依赖类型(Dependent Types) [^thinking-with-types] 100 | 101 | [^thinking-with-types]: https://leanpub.com/thinking-with-types 102 | [^type-level-programming-in-scala]: https://apocalisp.wordpress.com/2010/06/08/type-level-programming-in-scala/ 103 | 104 | > 注:关于类型体操这个说法是否有更早的来源,以及它和英文中 Mental Gymnastics 以及在俄语圈中据传是 Alexander Suvorov 所说的"数学是思维的体操(Математика - гимнастика ума)"的关系,暂时无法考证。如果读者有线索,可以联系我们。 105 | 106 | 函数式编程社区和学术界靠的比较近,而 TypeScript 社区则和工业界更近。随着 TypeScript 自身类型系统的能力和在 Web 应用开发者社区的影响力日渐增强,社区对 TypeScript 类型编程的研究文章和项目也逐渐增多。 107 | 108 | 国外社区里: 109 | 110 | 1. TypeScript's Type System is Turing Complete[^TypeScripts-Type-System-is-Turing-Complete]。早期关于 TypeScript 的类型系统的图灵完备性的讨论,是理解 TypeScript 类型编程绕不开的一篇文章。 111 | 1. HypeScript[^HypeScript]。一个纯由 TypeScript 类型实现的,TypeScript 解析器和类型检查器。 112 | 1. Meta-typing[^meta-typing]。收集了非常多类型编程的例子,包括排序(插入、快速、归并)、数据结构(列表、二叉树)、自然数算术以及一些谜题(迷宫、N 皇后)等等。 113 | 1. Type-challenges[^type-challenges]。一个带有在线判题功能的,具有难度标记的 TypeScript 类型编程习题集。包括简单到中等的常用的工具类型(`Awaited`、`Camelize`)的实现,和一些比较困难的问题(`Vue`的 this 类型,整数大小比较,`JSON`解析器)。这个仓库包括了几乎所有 TypeScript 类型编程可能用到的知识和技巧,可以当成类型编程的速查表使用。 114 | 1. Type-gymnastics[^type-gymnastics]。包括 URL 解析器、整数大小比较等问题的解答。 115 | 1. HKTS[^HKTS]。在 TypeScript 的类型系统中编码高阶类型。关于高阶类型是什么,我们之后会讨论。 116 | 1. Effect[^Effect]。通过类型编程实现类型安全的副作用管理。其中也使用到了高阶类型。 117 | 1. 国际象棋[^Chesskell]。通过类型编程实现了一个双人国际象棋。 118 | 119 | [^TypeScripts-Type-System-is-Turing-Complete]: https://github.com/microsoft/TypeScript/issues/14833 120 | [^HypeScript]: https://github.com/ronami/HypeScript 121 | [^meta-typing]: https://github.com/ronami/meta-typing 122 | [^Type-Challenges]: https://github.com/type-challenges/type-challenges 123 | [^type-gymnastics]: https://github.com/g-plane/type-gymnastics 124 | [^HKTS]: https://github.com/pelotom/hkts 125 | [^Effect]: https://github.com/Effect-TS/effect 126 | [^Chesskell]: https://dl.acm.org/doi/10.1145/3471874.3472987 127 | 128 | 在国内的 TypeScript 社区里也有一些非常有教益的文章(集): 129 | 130 | 1. 中国象棋[^type-chess]。如何通过类型编程实现一个中国象棋。 131 | 2. Lisp 解释器[^lisp-interpreter]。 132 | 3. 《Effective TypeScript:使用 TypeScript 的 n 个技巧》[^effective-ts-zhihu]。 133 | 4. "来玩 TypeScript 啊,机都给你开好了!"[^zhihu-typescript]。是一个知乎上的 TypeScript 专栏。 134 | 135 | [^type-chess]: https://github.com/chinese-chess-everywhere/type-chess 136 | [^lisp-interpreter]: https://zhuanlan.zhihu.com/p/427309936 137 | [^zhihu-typescript]: https://www.zhihu.com/column/c_206498766 138 | [^effective-ts-zhihu]: https://zhuanlan.zhihu.com/p/104311029 139 | 140 | ### 类型编程的配套设施 141 | 142 | 在进行类型编程的时候,我们需要保证类型符合预期或者在类型不符合预期的时候 Debug 代码。我们有如下设施: 143 | 144 | 1. 类型单元测试。 145 | 1. 类型嵌入提示。 146 | 147 | #### 类型单元测试 148 | 149 | 和运行时世界的单元测试一样,在类型世界也同样有单测来支持我们放心大胆地重构现有代码、测试驱动地开发新的类型。 150 | 151 | 区别是,在运行时世界里我们需要 Jest/Mocha/Vitest 这样的测试框架去执行测试,而类型世界的单测主要需要 TypeScript 编译器来做类型检查。 152 | 153 | 为了判断一个类型的计算结果符合预期,我们使用的工具主要有: 154 | 155 | 1. `Expect`。用来判断类型变量是`true`的子类型。因为字面量类型的子类型有且只有`never`和他本身,因此需要搭配`Equal`使用。 156 | 1. `Equal`。判断两个类型是否严格相等。 157 | 158 | 可以从`@type-challenges/utils`导入: 159 | 160 | ```ts 161 | import type { Expect, Equal } from '@type-challenges/utils'; 162 | ``` 163 | 164 | 其源码如下, 165 | 166 | ```ts 167 | export type Expect = T; 168 | export type Equal = (() => T extends X ? 1 : 2) extends < 169 | T, 170 | >() => T extends Y ? 1 : 2 171 | ? true 172 | : false; 173 | ``` 174 | 175 | 1. `// @ts-expect-error` 注释。若下面一行不存在类型错误,则这个注释会导致类型检查时报错。需要断言某个类型会产生错误时使用。例如: 176 | 177 | ```ts 178 | type TestCases = [ 179 | // @ts-expect-error Array 是个泛型,不传入类型参数而单独存在会报错 180 | Array, 181 | ]; 182 | ``` 183 | 184 | 在`*.ts`文件中书写类型单元测试即可。 通常,我们会用类型检查来跑单元测试,例如调用`tsc`: 185 | 186 | ``` 187 | tsc --noEmit 188 | ``` 189 | 190 | 其中`--noEmit`表示不产出编译结果。若检查没有报错,说明类型的单元测试通过了。 191 | 192 | 另外,在测试时把`test`目录和`src`目录包括在内,而在发布时不处理`test`目录下的文件也是一个很常见的需求。 193 | 若需要在测试时指定配置文件,可以使用`-p [config file]`来指定配置文件,如:`tsc --noEmit -p tsconfig.test.json`。 194 | 195 | `tsconfig.test.json`可以放在项目原本的`tsconfig.json`旁边并继承它。接着,可以视需要修改`include`配置,决定将哪些文件包括进来。例如: 196 | 197 | ```json 198 | { 199 | "extends": "./tsconfig.json", // 未指明的项继承自此配置 200 | "include": ["src/*", "test/*"] // 包括src和test目录下的文件 201 | } 202 | ``` 203 | 204 | #### 类型嵌入提示 205 | 206 | 我们在 Debug 的时候需要关心某些语言元素(即,类型或值)的类型。但每次将鼠标 hover 到类型或者变量上去看 QuickInfo 效率不高,我们通常用类型嵌入提示查询元素的类型。 207 | 208 | 类型嵌入提示主要是在开发时提供方便,并不能代替类型单元测试。 209 | 210 | 类型查询分为手动的基于注释的嵌入提示、自动的嵌入提示两种: 211 | 212 | 1. 基于注释的嵌入提示(Inlay Hint)。 213 | 214 | 1. TypeScript Playground[^typescript-playground] 内,写上`// ^?`,并让`^`的箭头对准你想要查询类型的元素(类型和值都可以),就会通过嵌入提示展示出类型,一目了然。 215 | 1. VS Code 中,也有类似插件 vscode-comment-queries [^vscode-comment-queries],同时支持 Python/Go 等语言,和更加丰富的查询语法(如,`// _?` 查询`_`下一行同一个列的元素的类型)。 216 | 217 | ![Inlay Hint](./assets/inlay-hint.jpg) 218 | 219 | 1. 自动嵌入提示。 220 | 1. VS Code 和 WebStorm 均可在设置中开启 JavaScript/TypeScript 类型的嵌入提示。关于要对哪些元素进行自动的类型嵌入提示,同样可以配置,请自行探索。 221 | 222 | [^typescript-playground]: https://www.typescriptlang.org/play 223 | [^vscode-comment-queries]: https://marketplace.visualstudio.com/items?itemName=YiJie.vscode-comment-queries 224 | 225 | #### 性能诊断 226 | 227 | 若想获得类型检查的过程的观测性数据,可以启用`tsc`的`--diagnostics`标志: 228 | 229 | ```shell 230 | tsc --diagnostics 231 | ``` 232 | 233 | 执行后会额外输出一段诊断信息,展示类型检查的过程的一些计数器。例如,标识符(Identifiers)、符号(Symbols)和实例化(Instantiations,即泛型类型被填上参数成为具体类型的过程)。 234 | 235 | ``` 236 | Files: 464 237 | Lines: 103012 238 | Identifiers: 126477 239 | Symbols: 1196143 240 | Types: 593053 241 | Instantiations: 675088 242 | Memory used: 619829K 243 | I/O read: 0.05s 244 | I/O write: 0.00s 245 | Parse time: 0.38s 246 | Bind time: 0.14s 247 | Check time: 2.39s 248 | Emit time: 0.00s 249 | Total time: 2.91s 250 | ``` 251 | 252 | ## 通过 TypeScript 到其类型系统的嵌入理解类型编程 253 | 254 | 那么,我们应该如何理解 TypeScript 中的类型编程? 255 | 256 | ### TypeScript 到其类型系统的嵌入 257 | 258 | #### 值编程-类型编程的对应关系 259 | 260 | | 值编程的元素 | 类型编程的元素 | 261 | | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 262 | | 常量声明 `const a = ...` | 类型声明 `type a = ...` | 263 | | 实例测试 `a instanceof b` | 条件类型 `a extends b ? ... : ...` | 264 | | 布尔表达式条件语句 `if (a) {b} else {c}` | 条件类型 `a extends true ? b : c` | 265 | | 函数定义 `function A(b) {...}` | 泛型定义 `type A = ...;` | 266 | | 函数参数和返回值的类型标注 `function A(b: Ty): C {...}` | 泛型参数类型和返回值类型标注 `type A = _returns;` | 267 | | 函数应用 `A(b)` | 泛型实例化 `A` | 268 | | 列表 `[]` | 元组 `[]` | 269 | | 列表长度 `[].length` | 元组长度 `[]['length']` | 270 | | 字面量 `1` | 字面量类型 `type A = 1; type B = '字符串字面量';` | 271 | | 自然数 `0`, `1`, `2`,... | 一进制数 `type Nat = 1[]; type Zero = []; type One=[1]; type Two = [1, 1]; ...` | 272 | | - | 一进制数转换为字面量类型 `One['length']` | 273 | | 自然数加法 `const add = (a: number, b: number) => a + b` | 元组连接 `type Add = [...a, ...b];` | 274 | | 抛出异常 `throw` | 让计算过程返回`never` | 275 | | 模式匹配 (JavaScript 无此特性) | 子类型测试中的类型推导 `arr extends [infer cur, ... infer rest] ? tail : never` | 276 | | 严格相等 `_.equal(a, b)` | `Equal` 工具泛型 `Equal` | 277 | | `reduce`实现迭代 `const sum = (nums: number[], init: number)=>nums.reduce((acc,cur)=> acc+cur, init)` | 使用递归泛型模拟迭代过程 `type Sum = arr extends [infer cur, ... infer rest] ? Sum> : result;` | 278 | | 高阶函数 const apply = (f, arg) => f(arg) | 编码高阶类型 `type Apply = 将泛型f以arg为参数进行实例化;` | 279 | 280 | > 注: 281 | > 282 | > 1. 类型编程的元素一栏中,有些代码块并不是完整的,需要将其声明为一个类型,即在前面加上`type XXX = `才符合 TypeScript 的类型语言语法。 283 | > 1. 泛型类型也可以理解为类型层面的函数,因为它接受一些类型返回另外一个类型,正如值空间中的函数接受一些值返回另外一个值。另可称呼为类型函数(Type Functions)、类型构造器(Type Constructors)、类型算子(Type Operators),本文为了便于理解,采用了泛型类型的称呼。 284 | 285 | 自然数在 TypeScript 类型编程中的编码极为重要,因此我们着重介绍一下: 286 | 287 | 我们将自然数类型`Nat`定义为一个长度不定的数组,其中的元素的类型可以任意选取,这里我们选取`unknown`作为数组元素。 288 | 289 | ```ts 290 | type Nat = Array; 291 | ``` 292 | 293 | 这样一来,值空间的以下值都是 `Nat` 类型的: 294 | 295 | ```ts 296 | const zero: Nat = []; 297 | const one: Nat = [1]; 298 | const two: Nat = [1, 1]; 299 | const three: Nat = [1, 1, 1]; 300 | ``` 301 | 302 | `Nat`因为本质上是个 Array,我们若是取其`length`属性,会得到`number`,这也非常合理,因为 Array 的长度是不确定的,我们只知道他是个自然数。 303 | 304 | ```ts 305 | type NatLength = Nat['length']; // 得到 number 306 | ``` 307 | 308 | 接下来,我们会利用到 TypeScript 类型语言 的另外一个特性:元组。 309 | 310 | 元组是`Array`的特化形式,最重要的区别就是,元组是定长的:取元组的`length`会得到一个数字字面量类型。 311 | 312 | ```ts 313 | type Zero = []; 314 | type LengthOfZero = Zero['length']; // 得到 0 315 | type One = [1]; 316 | type LengthOfOne = One['length']; // 得到 1 317 | type Two = [1, 1]; 318 | type LengthOfTwo = Two['length']; // 得到 2 319 | ``` 320 | 321 | 此时,我们就能够通过元组连接实现自然数加法: 322 | 323 | ```ts 324 | type Add = [...a, ...b]; 325 | type Three = Add; 326 | type LengthOfThree = Three['length']; 327 | ``` 328 | 329 | 另外,我们可以通过条件类型的`infer`关键字得到元组的第一项和去掉这一项的剩余元组。这个操作也非常常用,通常叫作`Head`和`Tail`: 330 | 331 | ```ts 332 | type IsNotEmpty = a['length'] extends 0 ? false : true; 333 | type Head = a extends [infer head, ...infer tail] 334 | ? head 335 | : never; 336 | type Tail = a extends [infer head, ...infer tail] ? tail : []; 337 | ``` 338 | 339 | #### 高阶类型的困境 340 | 341 | 在 TypeScript 的值语言 (即,JavaScript) 中,我们可以构造高阶函数(Higher-order Functions):也就是输入或者返回值为函数的函数。 342 | 343 | ```ts 344 | function fold(nums: number[], f: (acc: number, cur: number) => number): number { 345 | let acc = 0; 346 | for (const num of nums) { 347 | acc = f(acc, num); 348 | } 349 | return acc; 350 | } 351 | ``` 352 | 353 | 上面,我们在 TypeScript 中实现了一个`fold`函数。它接受一个数字数组,和一个二元函数,将这个函数应用在"上一次应用的输出和数组的每一项上",最后把结果返回。 354 | 355 | 毫无疑问,`fold`函数以函数为参数,因此它是一个高阶函数,像这种高阶函数在 TypeScript 的标准库和实践中比比皆是。 356 | 357 | 我们的问题是,我们在类型编程中如何使用高阶函数?我们如何将这种结构翻译到类型上? 358 | 359 | 一个最直接的想法是,既然我们将函数翻译成为了泛型类型,那我们直接将泛型类型作为泛型类型的类型参数传入即可。此时,泛型类型就成了接受泛型类型的类型。类型系统的这种能力叫作高阶类型(Higher-kinded Types, HKT)。 360 | 361 | 很遗憾,在目前的 TypeScript 中,这样的代码无法通过类型检查,因为 TypeScript 本身不支持 HKT,无法把泛型类型的参数(也就是`f`)标记为一个泛型,也不支持将未实例化的泛型传来传去。 362 | 363 | ```ts 364 | type Fold< 365 | nums extends Nat[], 366 | f, 367 | acc extends Nat = [], 368 | > = IsNotEmpty extends true 369 | ? Fold, f, f>> // 报错:Type 'f' is not generic.ts(2315) 370 | : acc; 371 | type Test = Fold<[One, Two], Add>; // 报错:Generic type 'Add' requires 2 type argument(s).ts(2314) 372 | ``` 373 | 374 | 若是要将一个类型作为泛型类型的参数使用,这个类型就必不能是未实例化的泛型,必须是一个具体的类型。也就是说,我们需要把代码改成如下样子: 375 | 376 | ```ts 377 | type Fold< 378 | nums extends Nat[], 379 | f, 380 | acc extends Nat = [], 381 | > = IsNotEmpty extends true 382 | ? Fold, f, Apply]>> 383 | : acc; 384 | type Test = Fold<[One, Two], AddHKT>; 385 | // @ts-expect-error 386 | type AddHKT = Add的无参数版,里面包含两个隐式的占位符?; 387 | // @ts-expect-error 388 | type Apply = 将arguments应用在f上???; 389 | ``` 390 | 391 | 现在,让我们整理一下目标: 392 | 393 | 1. 找到一种将`Add`转换为`AddHKT`的方法。 394 | 2. 实现`Apply`。 395 | 396 | 完成了这两个目标,我们就成功地构造出了高阶类型,也就可以在类型编程中自由地传递泛型了。 397 | 398 | #### 高阶类型的实现及其扩展 399 | 400 | 在 TypeScript 社区中,也有不少关于高阶类型的研究,其中较新的一个实现来自 Effect [^Effect-Higher-Kinded-Types]. 401 | 402 | 下面定义了`HKT`这个 interface,用来表示有两个类型参数的泛型。可以看到,其`In1`和`In2`都是`unknown`类型的。 403 | 404 | ```ts 405 | interface HKT { 406 | readonly In1: unknown; 407 | readonly In2: unknown; 408 | } 409 | ``` 410 | 411 | `Apply`是一个泛型类型,接受一个`HKT`,和两个类型参数,负责将参数应用上去。 412 | 413 | ```ts 414 | type Apply = F extends { 415 | readonly type: unknown; 416 | } 417 | ? (F & { 418 | readonly In1: In1; 419 | readonly In2: In2; 420 | })['type'] 421 | : never; 422 | ``` 423 | 424 | 最后是这个方法的关键,`AddHKT`的实现: 425 | 426 | ```ts 427 | interface BasicAddHKT extends HKT { 428 | // @ts-expect-error Type 'this["In1"]' does not satisfy the constraint 'Nat'.ts(2344) 429 | type: Add; 430 | } 431 | type BasicAddHKT = Expect['length'], 3>>; 432 | ``` 433 | 434 | 其实现思路有如下要点: 435 | 436 | 1. 利用了`interface`具有类型上的`this`的特性,通过在`Apply`中增加对`In1`和`In2`的约束,让`In1`和`In2`从`unknown`变为传入的类型。 437 | 1. 利用了顶类型`unknown`的吸收性质:对于任意的类型`A`,`unknown & A`都是`A`本身。 438 | 439 | 这个实现基本解决了 HKT 的问题,但是仍然存在一些不足: 440 | 441 | 1. 无法通过类型检查。`Add`要求两个类型参数都是`Nat`的子类型,但是`BasicAddHKT`并没有办法保证这点。 442 | 2. 泛型类型的元数是固定的。对`BasicAddHKT`来说,它是一个 2 元的泛型类型,需要接受 2 个类型参数才能实例化。那么,对其他元数的泛型类型,我们就无法复用 HKT。 443 | 3. 不支持部分应用(Partial Application)而必须一次性传入所有的类型参数。它对应于值编程中的柯里化函数。 444 | 445 | 我们可以对它进行改进: 446 | 447 | 1. 利用`Assert`工具类型,将输入的类型参数`In1`和`In2`限制为`Nat`,消除不合法的路径。 448 | 1. 改造`Apply`得到`PartialApply`,使其支持部分应用。 449 | 1. 改造`HKT`类,并提供工具类型`HKTWithArity`,使其支持任意元数。 450 | 451 | 为了让这份代码通过类型检查,我们需要一个工具类型`Assert`。简单来说,它断言`T`是`P`的子类型。加上了这个断言,`Add`的两个参数就都必定为`Nat`类型了。 452 | 453 | ```ts 454 | type Assert = T extends P ? T : /* T若非P的子类型就报错 */ never; 455 | interface AddHKT extends HKT { 456 | type: Add, Assert>; // 没有类型错误了 457 | } 458 | type TestAddHKT = Apply['length']; 459 | ``` 460 | 461 | 接着,我们可以改造`Apply`,得到`PartialApply`。其核心逻辑是: 462 | 463 | 1. 检查到传入的`lambda`还需要几个类型参数。 464 | 2. 若为 0 个,`lambda['type']`已经存储着一个实例化完毕的类型,直接返回`lambda['type']`。 465 | 3. 若还需要类型参数,尝试从 `arguments` 中拿一个元素。若`arguments`已空,直接返回`lambda`。否则,进行一次应用,并回到第 1 步。 466 | 467 | ```ts 468 | type PartialApply = lambda extends HKT 469 | ? arguments['length'] extends 0 470 | ? Equal extends false 471 | ? lambda['type'] 472 | : lambda 473 | : PartialApply, TAIL> 474 | : lambda; 475 | type TestApplication = [ 476 | Expect, number>>, 477 | Expect< 478 | Equal< 479 | PartialApply, [number]>, 480 | Map 481 | > 482 | >, 483 | ]; 484 | ``` 485 | 486 | 接下来,我们改造`HKT`类,并提供工具类型`HKTWithArity`,使其支持任意元数(Arity)。 487 | 488 | ```ts 489 | type MakeArityConstraint< 490 | T extends number, 491 | res_nat extends unknown[] = [], 492 | > = Equal extends true 493 | ? unknown[] 494 | : T extends 0 495 | ? [] 496 | : Equal extends true 497 | ? res_nat 498 | : MakeArityConstraint; 499 | 500 | type TestMakeArityConstraint = [ 501 | Expect, []>>, 502 | Expect, [unknown]>>, 503 | Expect, [unknown, unknown]>>, 504 | ]; 505 | 506 | interface HKTWithArity extends HKT { 507 | readonly TypeArguments: MakeArityConstraint; 508 | } 509 | ``` 510 | 511 | 这样一来,我们就可以改写`AddHKT`,让它继承`HKTWithArity<2>`,实现对元数的约束。 512 | 513 | ```ts 514 | interface BetterAddHKT extends HKTWithArity<2> { 515 | type: Add< 516 | Assert, 517 | Assert 518 | >; 519 | } 520 | ``` 521 | 522 | 另外,它可以支持递归。 523 | 524 | ```ts 525 | interface TreeHKT extends HKTWithArity<1> { 526 | type: this extends infer A extends this 527 | ? { value: A['TypeArguments']['0']; nodes: A['type'][] } 528 | : never; 529 | } 530 | 531 | type NumberTreeHKTInstance = PartialApply; 532 | // ^? 533 | 534 | declare const tree: NumberTreeHKTInstance; 535 | 536 | const value = tree.nodes[0]?.nodes[0]?.nodes[0]?.nodes[0]?.nodes[0]; 537 | 538 | type NumberTree = { value: number; nodes: NumberTree[] }; 539 | type TestRecursive = [ 540 | Expect, NumberTree>>, 541 | Expect>, 542 | Expect>, 543 | ]; 544 | ``` 545 | 546 | 目前为止,我们得到了一个比较完善的实现。这个实现仍有一些值得改进的点,但是我们已经基本上达到我们的目的了。 547 | 548 | 1. 仍然依赖`Assert`进行类型断言。我们可以考虑引入类型参数的参考数组,保证每一个类型参数都是参考数组对应位置上元素的子类型。 549 | 550 | [^Effect-Higher-Kinded-Types]: https://www.effect.website/docs/behaviour/hkt 551 | 552 | > 注:HKTS 使用占位符实例化泛型,再对实例递归替换占位符来实现 HKT [^HKTS]。这种思路是无法用在`Add`上的。因为 Add 在`[...a, ...b]`时会尝试将占位符`a`和`b`展开,此时会得到`any[]`,导致后续进行递归替换的时候找不到占位符。此外,HKTS 的方法不支持递归数据类型。 553 | 554 | ### TypeScript 代码到其类型系统嵌入的自动翻译器 555 | 556 | 若要将 TypeScript 代码翻译成类型语言,我们有两条路径: 557 | 558 | 1. 虚拟机。请参考`./src/vm`下的代码,简单实现了一个基于栈的虚拟机。本质上是在类型系统上面实现了一个 JavaScript 解释器。 559 | 1. 子集翻译。为了更好地理解 TypeScript 类型层编程的性质,我们需要定义一个 TypeScript 的图灵完备的子集,将这个子集翻译成 TypeScript 的类型语言。完整实现正在工作中,请参考`./transformer-plugin.ts`下的代码。 560 | 561 | #### TypeScript 子集的定义 562 | 563 | 这个子集需要满足以下性质: 564 | 565 | 1. 静态单赋值(Static Single Assignment, SSA)。所有变量必须用 const 声明,被赋值且仅被赋值一次。这要求我们除初始化之外,不可以使用赋值(`=`)运算符。 566 | 2. 函数纯净。支持高阶函数作为函数的参数,但是函数不可以引用自由变量;自定义的函数不存在副作用。 567 | 3. 语法简单。保持语法尽量少,在实现翻译器的时候不必处理过多的语法。处理边界情况不是我们关心的。 568 | 569 | #### TypeScript 子集的翻译 570 | 571 | 1. 函数。我们将它翻译成泛型类型。对于高阶函数,我们将其用之前详细叙述的 HKT 方法翻译成为 HKT。我们的 HKT 翻译的方法可以支持递归。 572 | 1. 变量声明。我们将变量声明统一提升为泛型类型上带默认值的参数。 573 | 1. 自然数和布尔值,及其上面的操作符。翻译成为泛型类型。 574 | 1. 条件语句。翻译成条件类型语法`a extends b ? ... : ...`。 575 | 576 | ## 结语:从类型编程到类型驱动开发 577 | 578 | ### 重新思考类型编程的价值 579 | 580 | 谈到类型编程,有一个避不开的问题:类型编程究竟是没事找事的消遣,还是对开发者来说真有其价值? 581 | 582 | 本文对此持实用主义的立场:进行恰当的类型编程确实有其价值。 583 | 584 | 仅仅只是将值编程中非常容易实现的事情用类型编程重写一遍的类型体操,纯粹是为了消遣或者在理论上验证一个想法,很难说具有什么实用价值。 585 | 586 | 而对库设计的场景来说,一个有一定复杂度的类型带来的很可能是类型安全的接口和开发者良好的补全体验,更不用说能够把许多潜在的错误在编译期暴露出来了。举个例子,若是 Vue 2 在一开始就通过类型编程提供完善的类型定义,甚至为了类型安全反过来约束框架本身的设计,那么开发者就不必在使用 TypeScript 时面对满屏幕的 any 了,也能够将一些不合法的调用拦在编译期。 587 | 588 | 再考虑业务开发的场景。假定我们需要写一个流程管理逻辑,由多个函数组成。我们必须要按照一定的顺序来组织这些流程。这就非常适合使用类型编程。例子改编自[^write-you-a-typescript]: 589 | 590 | [^write-you-a-typescript]: https://github.com/suica/write-you-a-typescript 591 | 592 | ```ts 593 | type Code = { fileList: string[]; addedTime: Date }; 594 | declare const LintInternalSymbol: unique symbol; 595 | type Linted = T & { [LintInternalSymbol]: undefined }; 596 | declare function lint(code: T): Linted; 597 | declare function commit(code: Linted): Promise; 598 | 599 | declare const code: Code; 600 | 601 | commit(code); // 类型错误,报错 602 | 603 | commit(lint(code)); // 正确,不报错 604 | ``` 605 | 606 | 总的来说,类型只是一个极为有效的对代码进行静态约束、对业务进行建模的手段。我们更应该把类型编程的一些技巧类比成设计模式(Design Patterns):模式不是目的,而是手段。过犹不及,我们不应该为了去使用某个模式而设计,而应当使用模式去改善我们的设计,让我们的设计不多也不少,刚好能够精确地描述业务本身。 607 | 608 | ### 如何掌握 TypeScript 类型编程 609 | 610 | 那么,作为一名开发者,如何掌握 TypeScript 类型编程?这里提供一个思路,仅供参考。 611 | 612 | - 步骤一:学习。掌握 TypeScript 类型编程,应当从基础知识开始。 613 | 614 | 1. 阅读 TypeScript 手册[^typescript-handbook]。 615 | 1. 解答 Type-challenges[^type-challenges]中尽量多的问题,同时在这个过程中反复阅读手册。 616 | 617 | [^typescript-handbook]: https://www.typescriptlang.org/docs/handbook/intro.html 618 | 619 | - 步骤二:实践。 620 | 621 | 1. 在平时的开发过程中发掘类型不合理的地方,并使用更加精准的类型来描述业务。非必要不做类型体操,除非它带来足够的收益。 622 | 1. 尝试使用类型先行的思想,实践类型驱动开发。在这个过程中,一定要用上 AI。有问题可以询问 ChatGPT 或者 Copilot,能够大大提高建模的效率。 623 | 1. 参与库的设计和改进和社区的讨论。一个充分利用类型系统的 API,能够把部分错误在编译期检查出来。 624 | 625 | - 步骤三:回到步骤一。 626 | 627 | > 注:避开"编程与类型系统"这本书[^编程与类型系统]。 628 | 629 | [^编程与类型系统]: https://book.douban.com/subject/35325133 630 | 631 |

参考文献

632 | 633 | [^Purely-Functional-Data-Structures]: https://www.cs.cmu.edu/~rwh/students/okasaki.pdf 634 | [^fp-ts]: https://github.com/gcanti/fp-ts 635 | [^Type-level-programming-with-match-types]: https://dl.acm.org/doi/10.1145/3498698 636 | 637 | [^Generative type abstraction and type-level computation]: https://dl.acm.org/doi/10.1145/1925844.1926411 638 | [^Refinement kinds: type-safe programming with practical type-level computation]: https://dl.acm.org/doi/10.1145/3360557 639 | [^Refinement types for TypeScript]: https://dl.acm.org/doi/10.1145/2908080.2908110 640 | -------------------------------------------------------------------------------- /assets/inlay-hint.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suica/typescript-type-level-programming/6bb5d2676fc7c21b1c66f5380f21b73125b412ee/assets/inlay-hint.jpg -------------------------------------------------------------------------------- /assets/overview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suica/typescript-type-level-programming/6bb5d2676fc7c21b1c66f5380f21b73125b412ee/assets/overview.png -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [['@babel/preset-env', { targets: { node: 'current' } }], 3 | '@babel/preset-typescript', 4 | ], 5 | }; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "typescript-type-level-programming", 3 | "version": "1.0.0", 4 | "main": "index.js", 5 | "repository": "git@github.com:suica/typescript-type-level-programming.git", 6 | "author": "Sg ", 7 | "license": "MIT", 8 | "scripts": { 9 | "test": "jest" 10 | }, 11 | "dependencies": { 12 | "@babel/code-frame": "^7.18.6", 13 | "@babel/template": "^7.22.15", 14 | "@babel/traverse": "^7.23.6", 15 | "@babel/types": "^7.18.8", 16 | "lodash-es": "^4.17.21", 17 | "prettier": "^2.7.1", 18 | "ts-node": "^10.2.1", 19 | "typescript": "5.4.0-dev.20231214" 20 | }, 21 | "devDependencies": { 22 | "@babel/core": "^7.16.5", 23 | "@babel/generator": "^7.16.5", 24 | "@babel/parser": "^7.16.6", 25 | "@babel/plugin-transform-typescript": "^7.16.1", 26 | "@babel/preset-env": "^7.16.5", 27 | "@babel/preset-typescript": "^7.16.5", 28 | "@type-challenges/utils": "^0.1.1", 29 | "@types/babel__code-frame": "^7.0.3", 30 | "@types/babel__core": "^7.20.5", 31 | "@types/babel__generator": "^7.6.7", 32 | "@types/babel__template": "^7.4.4", 33 | "@types/babel__traverse": "^7.20.4", 34 | "@types/jest": "^27.0.3", 35 | "@types/lodash": "^4.14.202", 36 | "@types/lodash-es": "^4.17.6", 37 | "@types/node": "^16.11.6", 38 | "babel-jest": "^27.4.5", 39 | "jest": "^27.4.5" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/entry/main.spec.ts: -------------------------------------------------------------------------------- 1 | import { transform } from '@babel/core'; 2 | import TypeScriptToTypePlugin from '../modules/transformer/transformer-plugin'; 3 | describe('main entry', () => { 4 | it.skip('should work', () => { 5 | const result = transform('const a = 1;', { 6 | plugins: [TypeScriptToTypePlugin], 7 | filename: 'test.ts', 8 | }); 9 | }); 10 | }); 11 | -------------------------------------------------------------------------------- /src/entry/main.ts: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suica/typescript-type-level-programming/6bb5d2676fc7c21b1c66f5380f21b73125b412ee/src/entry/main.ts -------------------------------------------------------------------------------- /src/modules/compiler.ts: -------------------------------------------------------------------------------- 1 | import generate from '@babel/generator'; 2 | import * as parser from '@babel/parser'; 3 | import { expression } from '@babel/template'; 4 | import traverse from '@babel/traverse'; 5 | import { Statement } from '@babel/types'; 6 | 7 | export function compile(code: string) { 8 | const ast = parser.parse(code); 9 | let res = ''; 10 | traverse(ast, { 11 | enter(path) { 12 | if (path.isVariableDeclaration()) { 13 | 14 | } 15 | // if (path.isIdentifier({ name: 'a' })) { 16 | // const aa = expression`x`(); 17 | // path.replaceInline(aa); 18 | // } 19 | }, 20 | exit(path) { 21 | // path.traverse(visitor, state) 22 | } 23 | }); 24 | return generate(ast).code; 25 | } 26 | -------------------------------------------------------------------------------- /src/modules/helpers/helpers.enum.ts: -------------------------------------------------------------------------------- 1 | export enum HelperTypeEnum { 2 | LTE = 'LTE', 3 | SUB = 'SUB', 4 | LT = 'LT', 5 | EQUALS = 'EQUALS', 6 | NOT = 'NOT', 7 | AND = 'AND', 8 | OR = 'OR', 9 | } 10 | 11 | export const helperTypesKeys = Object.keys(HelperTypeEnum) as HelperTypeEnum[]; 12 | 13 | // type SUB
= A extends [...B, ...infer C] 14 | // ? C 15 | // : []; 16 | // type LTE = SUB extends [] 17 | // ? true 18 | // : false; 19 | 20 | // type EQUALS = (() => T extends X ? 1 : 2) extends () => T extends Y 21 | // ? 1 22 | // : 2 23 | // ? true 24 | // : false; 25 | 26 | // type NOT = T extends true ? false : true; 27 | 28 | // type C = NOT; 29 | 30 | // type AND = A extends true 31 | // ? B extends true 32 | // ? true 33 | // : false 34 | // : false; 35 | 36 | // type OR = A extends true 37 | // ? true 38 | // : B extends true 39 | // ? true 40 | // : false; 41 | 42 | // type LT = LTE extends [] 43 | // ? EQUALS extends false 44 | // ? true 45 | // : false 46 | // : false; 47 | 48 | export const helperTypesSourceCodeMap: Record = { 49 | [HelperTypeEnum.SUB]: ` 50 | type SUB = A extends [...B, ...infer C] 51 | ? C 52 | : []; 53 | `, 54 | [HelperTypeEnum.EQUALS]: ` 55 | type EQUALS = (() => T extends X ? 1 : 2) extends () => T extends Y 56 | ? 1 57 | : 2 58 | ? true 59 | : false; 60 | `, 61 | [HelperTypeEnum.LTE]: ` 62 | type LTE = SUB extends [] 63 | ? true 64 | : false; 65 | `, 66 | [HelperTypeEnum.NOT]: ` 67 | type NOT = T extends true ? false : true; 68 | `, 69 | [HelperTypeEnum.LT]: ` 70 | type LT = LTE extends [] 71 | ? EQUALS extends false 72 | ? true 73 | : false 74 | : false; 75 | `, 76 | [HelperTypeEnum.AND]: ` 77 | type AND = A extends true 78 | ? B extends true 79 | ? true 80 | : false 81 | : false; 82 | `, 83 | [HelperTypeEnum.OR]: ` 84 | type OR = A extends true 85 | ? true 86 | : B extends true 87 | ? true 88 | : false; 89 | `, 90 | }; 91 | -------------------------------------------------------------------------------- /src/modules/helpers/helpers.ts: -------------------------------------------------------------------------------- 1 | 2 | import * as t from '@babel/types'; 3 | export function buildTypeApplicationNode(typename: string, typeArgs: t.TSType[]): t.TSTypeReference { 4 | return t.tsTypeReference(t.identifier(typename), t.tsTypeParameterInstantiation(typeArgs)); 5 | } -------------------------------------------------------------------------------- /src/modules/playground/effect-hkt.ts: -------------------------------------------------------------------------------- 1 | import { Add } from "../vm/utils/nat"; 2 | 3 | type Nat = Array<1>; 4 | 5 | interface HKT { 6 | readonly In1: unknown; 7 | readonly In2: unknown; 8 | } 9 | 10 | type Apply = F extends { 11 | readonly type: unknown; 12 | } 13 | ? (F & { 14 | readonly In1: In1; 15 | readonly In2: In2; 16 | })['type'] 17 | : never; 18 | 19 | interface BasicAddHKT extends HKT { 20 | // @ts-expect-error Type 'this["In1"]' does not satisfy the constraint 'Nat'.ts(2344) 21 | type: Add; 22 | } 23 | 24 | type Assert = T extends P ? T : never; 25 | interface AddHKT extends HKT { 26 | type: Add, Assert>; 27 | } 28 | type Three = Apply['length']; // 3 29 | -------------------------------------------------------------------------------- /src/modules/playground/hkt.ts: -------------------------------------------------------------------------------- 1 | import {type Expect } from '@type-challenges/utils'; 2 | import { TAIL } from '../vm/utils/helper'; 3 | import { EQUALS } from '../vm/utils/nat'; 4 | 5 | // code adapted from https://www.effect.website/docs/behaviour/hkt#what-are-higher-kinded-types 6 | 7 | type MakeArityConstraint< 8 | T extends number, 9 | res_nat extends unknown[] = [], 10 | > = EQUALS extends true 11 | ? unknown[] 12 | : T extends 0 13 | ? [] 14 | : EQUALS extends true 15 | ? res_nat 16 | : MakeArityConstraint; 17 | 18 | type TestMakeArityConstraint = [ 19 | Expect, []>>, 20 | Expect, [unknown]>>, 21 | Expect, [unknown, unknown]>>, 22 | ]; 23 | 24 | type ReplaceFirstUnknownWith< 25 | Arr extends any[], 26 | item, 27 | result extends any[] = [], 28 | > = Arr['length'] extends 0 29 | ? result 30 | : EQUALS extends true 31 | ? [...result, item, ...TAIL] 32 | : ReplaceFirstUnknownWith, item, [...result, Arr[0]]>; 33 | 34 | type TestReplaceFirstUnknownWith = [ 35 | Expect< 36 | EQUALS< 37 | ReplaceFirstUnknownWith<[unknown, unknown], number>, 38 | [number, unknown] 39 | > 40 | >, 41 | Expect< 42 | EQUALS, [number, number]> 43 | >, 44 | Expect, []>>, 45 | ]; 46 | 47 | export interface HKT { 48 | readonly TypeArguments: unknown[]; 49 | readonly type?: unknown; 50 | } 51 | export interface ArrayHKT extends HKTWithArity<1> { 52 | readonly type: Array; 53 | } 54 | 55 | type SingleApplication = F & { 56 | readonly TypeArguments: ReplaceFirstUnknownWith< 57 | F['TypeArguments'], 58 | TypeArgument 59 | >; 60 | }; 61 | type Kind = EQUALS< 62 | SingleApplication['TypeArguments'][number], 63 | unknown 64 | > extends false 65 | ? SingleApplication['type'] 66 | : SingleApplication; 67 | 68 | type TestKind = [ 69 | Expect, string[]>>, 70 | Expect, number[]>>, 71 | Expect, number>, Map>>, 72 | ]; 73 | 74 | interface Mappable { 75 | readonly map: (self: Kind, f: (a: A) => B) => Kind; 76 | } 77 | 78 | const stringify = 79 | (T: Mappable) => 80 | (self: Kind): Kind => 81 | T.map(self, (n) => { 82 | type test = Expect>; 83 | return `number: ${n}`; 84 | }); 85 | 86 | export interface HKTWithArity extends HKT { 87 | readonly TypeArguments: MakeArityConstraint; 88 | } 89 | export type PartialApply = lambda extends HKT 90 | ? arguments['length'] extends 0 91 | ? EQUALS extends false 92 | ? lambda['type'] 93 | : lambda 94 | : PartialApply, TAIL> 95 | : lambda; 96 | 97 | type CountUnknown< 98 | Arr extends any[], 99 | result extends number[] = [], 100 | > = Arr['length'] extends 0 101 | ? result['length'] 102 | : CountUnknown< 103 | TAIL, 104 | [...result, ...(EQUALS extends true ? [1] : [])] 105 | >; 106 | 107 | type Arity = T extends HKTWithArity 108 | ? EQUALS extends true 109 | ? number 110 | : CountUnknown 111 | : 0; 112 | 113 | interface MapHKT extends HKTWithArity<2> { 114 | type: Map; 115 | } 116 | 117 | type AnotherMapHKT< 118 | TypeArguments extends MakeArityConstraint<2> = MakeArityConstraint<2>, 119 | > = { type: Map }; 120 | 121 | type TestSingleApplicationArity = [ 122 | Expect['type'], Map>>, 123 | Expect['type'], Map>>, 124 | ]; 125 | type TestArity = [ 126 | Expect>, 0>>, 127 | Expect, 0>>, 128 | Expect, 0>>, 129 | Expect, 1>>, 130 | Expect, number>>, 131 | Expect, 2>>, 132 | ]; 133 | 134 | type TestApplication = [ 135 | Expect, string[]>>, 136 | Expect>, 1>>, 137 | Expect, Map>>, 138 | Expect< 139 | EQUALS, Map> 140 | >, 141 | Expect, number>>, 142 | Expect< 143 | EQUALS< 144 | PartialApply, [number]>, 145 | Map 146 | > 147 | >, 148 | ]; 149 | 150 | interface TreeHKT extends HKTWithArity<1> { 151 | type: this extends infer A extends this ? { value: A['TypeArguments']['0'], nodes: A['type'][] } : never; 152 | } 153 | 154 | type NumberTreeHKTInstance = PartialApply 155 | // ^? 156 | 157 | declare const tree: NumberTreeHKTInstance; 158 | 159 | const value = tree.nodes[0]?.nodes[0]?.nodes[0]?.nodes[0]?.nodes[0]; 160 | 161 | type NumberTree = {value: number, nodes: NumberTree[]}; 162 | 163 | type TestRecursive = [ 164 | Expect, NumberTree>>, 165 | Expect>, 166 | Expect>, 167 | ]; 168 | -------------------------------------------------------------------------------- /src/modules/playground/hkts.ts: -------------------------------------------------------------------------------- 1 | // code from https://github.com/pelotom/hkts?tab=readme-ov-file 2 | 3 | declare const index: unique symbol; 4 | 5 | /** 6 | * Placeholder representing an indexed type variable. 7 | */ 8 | export interface _ { 9 | [index]: N; 10 | } 11 | export type _0 = _<0>; 12 | export type _1 = _<1>; 13 | export type _2 = _<2>; 14 | export type _3 = _<3>; 15 | export type _4 = _<4>; 16 | export type _5 = _<5>; 17 | export type _6 = _<6>; 18 | export type _7 = _<7>; 19 | export type _8 = _<8>; 20 | export type _9 = _<9>; 21 | 22 | declare const fixed: unique symbol; 23 | 24 | /** 25 | * Marks a type to be ignored by the application operator `$`. This is used to protect 26 | * bound type parameters. 27 | */ 28 | export interface Fixed { 29 | [fixed]: T; 30 | } 31 | 32 | /** 33 | * Type application (simultaneously substitutes all placeholders within the target type) 34 | */ 35 | // prettier-ignore 36 | export type $ = ( 37 | T extends Fixed ? { [indirect]: U } : 38 | T extends _ ? { [indirect]: S[N] } : 39 | T extends undefined | null | boolean | string | number ? { [indirect]: T } : 40 | T extends (infer A)[] & { length: infer L } ? { 41 | [indirect]: L extends keyof TupleTable 42 | ? TupleTable[L] 43 | : $[] 44 | } : 45 | T extends (...x: infer I) => infer O ? { [indirect]: (...x: $) => $ } : 46 | T extends object ? { [indirect]: { [K in keyof T]: $ } } : 47 | { [indirect]: T } 48 | )[typeof indirect]; 49 | 50 | /** 51 | * Used as a level of indirection to avoid circularity errors. 52 | */ 53 | declare const indirect: unique symbol; 54 | 55 | /** 56 | * Allows looking up the type for a tuple based on its `length`, instead of trying 57 | * each possibility one by one in a single long conditional. 58 | */ 59 | // prettier-ignore 60 | type TupleTable = { 61 | 0: []; 62 | 1: T extends [ 63 | infer A0 64 | ] ? [ 65 | $ 66 | ] : never 67 | 2: T extends [ 68 | infer A0, infer A1 69 | ] ? [ 70 | $, $ 71 | ] : never 72 | 3: T extends [ 73 | infer A0, infer A1, infer A2 74 | ] ? [ 75 | $, $, $ 76 | ] : never 77 | 4: T extends [ 78 | infer A0, infer A1, infer A2, infer A3 79 | ] ? [ 80 | $, $, $, $ 81 | ] : never 82 | 5: T extends [ 83 | infer A0, infer A1, infer A2, infer A3, infer A4 84 | ] ? [ 85 | $, $, $, $, $ 86 | ] : never 87 | 6: T extends [ 88 | infer A0, infer A1, infer A2, infer A3, infer A4, infer A5 89 | ] ? [ 90 | $, $, $, $, $, $ 91 | ] : never 92 | 7: T extends [ 93 | infer A0, infer A1, infer A2, infer A3, infer A4, infer A5, infer A6 94 | ] ? [ 95 | $, $, $, $, $, $, $ 96 | ] : never 97 | 8: T extends [ 98 | infer A0, infer A1, infer A2, infer A3, infer A4, infer A5, infer A6, infer A7 99 | ] ? [ 100 | $, $, $, $, $, $, $, $ 101 | ] : never 102 | 9: T extends [ 103 | infer A0, infer A1, infer A2, infer A3, infer A4, infer A5, infer A6, infer A7, infer A8 104 | ] ? [ 105 | $, $, $, $, $, $, $, $, $ 106 | ] : never 107 | 10: T extends [ 108 | infer A0, infer A1, infer A2, infer A3, infer A4, infer A5, infer A6, infer A7, infer A8, infer A9 109 | ] ? [ 110 | $, $, $, $, $, $, $, $, $, $ 111 | ] : never 112 | } 113 | -------------------------------------------------------------------------------- /src/modules/playground/samples.ts: -------------------------------------------------------------------------------- 1 | import { HKTWithArity, PartialApply } from './hkt'; 2 | 3 | type Nat = Array; 4 | type IsNotEmpty = a['length'] extends 0 ? false : true; 5 | type Head = a extends [infer head, ...infer tail] 6 | ? head 7 | : never; 8 | type Tail = a extends [infer head, ...infer tail] ? tail : []; 9 | type Add = [...a, ...b]; 10 | 11 | type Zero = []; 12 | type LengthOfZero = Zero['length']; // 得到 0 13 | type One = [1]; 14 | type LengthOfOne = One['length']; // 得到 1 15 | type Two = [1, 1]; 16 | 17 | type BadFold< 18 | nums extends Nat[], 19 | f, 20 | acc extends Nat = [], 21 | > = IsNotEmpty extends true 22 | ? //@ts-expect-error 23 | BadFold, f, f>> 24 | : acc; 25 | //@ts-expect-error 26 | type TestBadFold = BadFold<[One, Two], Add>; 27 | 28 | type Assert = T extends P ? T : never; 29 | export interface AddHKT extends HKTWithArity<2> { 30 | type: Add< 31 | Assert, 32 | Assert 33 | >; 34 | } 35 | 36 | type ShouldBeThree = PartialApply['length']; 37 | // ^? 38 | -------------------------------------------------------------------------------- /src/modules/transformer/transformer-plugin.spec.ts: -------------------------------------------------------------------------------- 1 | import { transformSync } from '@babel/core'; 2 | import TypeScriptToTypePlugin from './transformer-plugin'; 3 | 4 | function transpileHelper(sourceCode: string) { 5 | const result = transformSync(sourceCode, { 6 | filename: 'test.ts', 7 | plugins: [TypeScriptToTypePlugin, '@babel/plugin-syntax-typescript'], 8 | configFile: false, 9 | }); 10 | return result?.code ?? ''; 11 | } 12 | 13 | describe('transpiler', () => { 14 | it('should work for simple type declaration', () => { 15 | expect(transpileHelper(`const a = 0;`)).toBe('type a = [];'); 16 | expect(transpileHelper(`const a = 1;`)).toBe('type a = [1];'); 17 | expect(transpileHelper(`const a = 2;`)).toBe('type a = [1, 1];'); 18 | expect(transpileHelper(`const a = 10;`)).toBe( 19 | 'type a = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1];' 20 | ); 21 | }); 22 | 23 | it('should work for simple single-statement functions', () => { 24 | expect( 25 | transpileHelper(` 26 | function makeZero(){ 27 | return 0; 28 | } 29 | `) 30 | ).toBe(`type makeZero = [];`); 31 | 32 | expect( 33 | transpileHelper(` 34 | function makeZero(){ 35 | return 0; 36 | } 37 | const zero = makeZero(); 38 | `) 39 | ).toBe(`type makeZero = [];\ntype zero = makeZero;`); 40 | 41 | expect( 42 | transpileHelper(` 43 | function makeZero2(x: number){ 44 | return 0; 45 | } 46 | const a = makeZero2(10); 47 | const b = makeZero2(a); 48 | `) 49 | ).toBe( 50 | `type makeZero2 = [];\ntype a = makeZero2<[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]>;\ntype b = makeZero2;` 51 | ); 52 | 53 | expect( 54 | transpileHelper(` 55 | function add(x: number, y: number){ 56 | return x + y; 57 | } 58 | const b = add(1, 2); 59 | const c = add(c, 2); 60 | const d = add(b, c); 61 | `) 62 | ).toBe( 63 | 'type add = [...x, ...y];\ntype b = add<[1], [1, 1]>;\ntype c = add;\ntype d = add;' 64 | ); 65 | 66 | expect( 67 | transpileHelper(` 68 | function addOne(x: number){ 69 | return x+1; 70 | } 71 | function makeZero(){ 72 | return 0; 73 | } 74 | const a = addOne(makeZero()); 75 | `) 76 | ).toBe( 77 | `type addOne = [...x, ...[1]];\ntype makeZero = [];\ntype a = addOne;` 78 | ); 79 | }); 80 | 81 | it('should inject helper types for binary operator', () => { 82 | expect(transpileHelper(`const a = 1; const b = 2; const c = a + b;`)).toBe( 83 | `type a = [1];\ntype b = [1, 1];\ntype c = [...a, ...b];` 84 | ); 85 | expect(transpileHelper(`const a = 1; const b = 2; const c = a - b;`)).toBe( 86 | `type a = [1];\ntype b = [1, 1];\ntype c = SUB;` 87 | ); 88 | }); 89 | 90 | it('should inject helper types for simple binary relation', () => { 91 | expect(transpileHelper(`const a = 1; const b = 2; const c = a<=b;`)).toBe( 92 | `type a = [1];\ntype b = [1, 1];\ntype c = LTE;` 93 | ); 94 | expect(transpileHelper(`const a = 1; const b = 2; const c = a;` 96 | ); 97 | expect(transpileHelper(`const a = 1; const b = 2; const c = a===b;`)).toBe( 98 | `type a = [1];\ntype b = [1, 1];\ntype c = EQUALS;` 99 | ); 100 | expect(transpileHelper(`const a = 1; const b = 2; const c = a!==b;`)).toBe( 101 | `type a = [1];\ntype b = [1, 1];\ntype c = NOT>;` 102 | ); 103 | }); 104 | 105 | it.skip('should work for single functions with single if statement', () => { 106 | 107 | expect(transpileHelper(` 108 | function simple(x: number){ 109 | if(1<=x){ 110 | return x; 111 | }else{ 112 | return 1; 113 | } 114 | } 115 | const a = simple(0); 116 | const b = simple(a); 117 | `)).toBe(``); 118 | 119 | expect( 120 | transpileHelper(` 121 | function sub(x: number, y:number){ 122 | if(x<=y){ 123 | return 0; 124 | }else{ 125 | return x-y; 126 | } 127 | } 128 | `) 129 | ).toBe(``); 130 | }); 131 | 132 | it('should work for functions with ?: operators', () => { 133 | expect( 134 | transpileHelper(` 135 | function sub(x: number, y:number){ 136 | return x<=y ? 0 : x-y; 137 | } 138 | const a = sub(1, 2); 139 | `) 140 | ).toBe(`type sub = LTE extends true ? [] : SUB;\ntype a = sub<[1], [1, 1]>;`); 141 | 142 | expect(transpileHelper(` 143 | function fib(x:number){ 144 | return x<=1 ? x : fib(x-1) + fib(x-2); 145 | } 146 | `)).toBe(`type fib = LTE extends true ? x : [...fib>, ...fib>];`) 147 | 148 | }); 149 | 150 | it.skip('should work for simple recursive function', () => { 151 | expect( 152 | transpileHelper(` 153 | function fib(x:number){ 154 | if(x<=1){ 155 | return x; 156 | }else{ 157 | return fib(x-1) + fib(x-2); 158 | } 159 | } 160 | `) 161 | ).toBe(''); 162 | }); 163 | }); 164 | -------------------------------------------------------------------------------- /src/modules/transformer/transformer-plugin.ts: -------------------------------------------------------------------------------- 1 | import { Visitor } from '@babel/core'; 2 | import { NodePath } from '@babel/traverse'; 3 | import * as t from '@babel/types'; 4 | import { buildTypeApplicationNode } from '../helpers/helpers'; 5 | import { HelperTypeEnum } from '../helpers/helpers.enum'; 6 | import { repeatObject } from '../utils/general'; 7 | 8 | type HelperTypeSwitchStore = Partial>; 9 | 10 | class Transformer { 11 | 12 | helperTypesSwitch: HelperTypeSwitchStore = {}; 13 | buildTsTypeNodeByPath( 14 | path: NodePath< 15 | | t.Expression 16 | | t.FunctionDeclaration 17 | | t.PrivateName 18 | | t.BlockStatement 19 | | t.ReturnStatement 20 | | t.IfStatement 21 | | undefined 22 | | null 23 | > 24 | ): t.TSType { 25 | if (path.hasNode()) { 26 | if (path.isStringLiteral()) { 27 | return t.tsLiteralType(path.node); 28 | } else if (path.isNumericLiteral()) { 29 | const value = path.node.value; 30 | return t.tsTupleType( 31 | repeatObject(t.tsLiteralType(t.numericLiteral(1)), value) 32 | ); 33 | } else if (path.isPrivateName()) { 34 | throw path.buildCodeFrameError('PrivateName is not implemented'); 35 | } else if (path.isIdentifier()) { 36 | return t.tsTypeReference(path.node); 37 | } else if (path.isBinaryExpression()) { 38 | const left = path.get('left'); 39 | const right = path.get('right'); 40 | const typeArgs = [left, right].map((arg) => { 41 | return this.buildTsTypeNodeByPath(arg); 42 | }); 43 | if (path.node.operator === '+') { 44 | return t.tsTupleType([ 45 | t.tsRestType(this.buildTsTypeNodeByPath(left)), 46 | t.tsRestType(this.buildTsTypeNodeByPath(right)), 47 | ]); 48 | } else if (path.node.operator === '-') { 49 | return buildTypeApplicationNode(HelperTypeEnum.SUB, typeArgs); 50 | } else if (path.node.operator === '<=') { 51 | return buildTypeApplicationNode(HelperTypeEnum.LTE, typeArgs); 52 | } else if (path.node.operator === '>') { 53 | return buildTypeApplicationNode(HelperTypeEnum.NOT, [buildTypeApplicationNode(HelperTypeEnum.LTE, typeArgs)]); 54 | } else if (path.node.operator === '<') { 55 | return buildTypeApplicationNode(HelperTypeEnum.LT, typeArgs); 56 | } else if (path.node.operator === '>=') { 57 | return buildTypeApplicationNode(HelperTypeEnum.NOT, [buildTypeApplicationNode(HelperTypeEnum.LT, typeArgs)]); 58 | } else if (path.node.operator === '===') { 59 | return buildTypeApplicationNode(HelperTypeEnum.EQUALS, typeArgs); 60 | } else if (path.node.operator === '!==') { 61 | return buildTypeApplicationNode(HelperTypeEnum.NOT, [ 62 | buildTypeApplicationNode(HelperTypeEnum.EQUALS, typeArgs) 63 | ]); 64 | } else { 65 | throw path.buildCodeFrameError( 66 | `operator ${path.node.operator} is not implemented yet` 67 | ); 68 | } 69 | } else if (path.isLogicalExpression()) { 70 | const left = path.get('left'); 71 | const right = path.get('right'); 72 | const typeArgs = [left, right].map((arg) => { 73 | return this.buildTsTypeNodeByPath(arg); 74 | }); 75 | if (path.node.operator === '&&') { 76 | return buildTypeApplicationNode(HelperTypeEnum.AND, typeArgs); 77 | } else if (path.node.operator === '||') { 78 | return buildTypeApplicationNode(HelperTypeEnum.OR, typeArgs); 79 | } else { 80 | throw path.buildCodeFrameError( 81 | `operator ${path.node.operator} is not implemented yet` 82 | ); 83 | } 84 | } else if (path.isUnaryExpression()) { 85 | const typeArgs = [this.buildTsTypeNodeByPath(path.get('argument'))]; 86 | if (path.node.operator === '!') { 87 | return buildTypeApplicationNode(HelperTypeEnum.NOT, typeArgs); 88 | } else { 89 | throw path.buildCodeFrameError( 90 | `operator ${path.node.operator} is not implemented yet` 91 | ); 92 | } 93 | } else if (path.isBlockStatement()) { 94 | const body = path.get('body'); 95 | if (body.length === 0) { 96 | // regard empty block as undefined 97 | return t.tsUndefinedKeyword(); 98 | } else if (body.length === 1) { 99 | const stat = body[0]!; 100 | return this.buildTsTypeNodeByPath(stat); 101 | } else { 102 | throw path.buildCodeFrameError( 103 | 'block cannot have more statements than 1' 104 | ); 105 | } 106 | } else if (path.isReturnStatement()) { 107 | return this.buildTsTypeNodeByPath(path.get('argument')); 108 | } else if (path.isConditionalExpression()) { 109 | const test = this.buildTsTypeNodeByPath(path.get('test')); 110 | const consequent = this.buildTsTypeNodeByPath(path.get('consequent')); 111 | const alternate = this.buildTsTypeNodeByPath(path.get('alternate')); 112 | return t.tsConditionalType(test, t.tsLiteralType(t.booleanLiteral(true)), consequent, alternate); 113 | } else if (path.isCallExpression()) { 114 | const callee = path.get('callee'); 115 | const args = path.get('arguments') as NodePath[]; 116 | if (callee.isExpression()) { 117 | if (callee.isIdentifier()) { 118 | const typeCallee = this.buildTsTypeNodeByPath(callee) as t.TSTypeReference; 119 | const typeArgs = args.map((arg) => { 120 | return this.buildTsTypeNodeByPath(arg); 121 | }); 122 | if (typeArgs.length) { 123 | typeCallee.typeParameters = 124 | t.tsTypeParameterInstantiation(typeArgs); 125 | } 126 | return typeCallee; 127 | } else { 128 | throw callee.buildCodeFrameError('only identifier is supported'); 129 | } 130 | } else { 131 | throw callee.buildCodeFrameError('only expression it supported'); 132 | } 133 | } else { 134 | throw path.buildCodeFrameError( 135 | `handler of ${path.type} is not implemented` 136 | ); 137 | } 138 | } 139 | throw path.buildCodeFrameError('path is empty'); 140 | } 141 | buildTypeParamDeclaration( 142 | paths: NodePath[] 143 | ): t.TSTypeParameterDeclaration | null { 144 | if (paths.length === 0) { 145 | return null; 146 | } 147 | const h = paths as NodePath[]; 148 | return t.tsTypeParameterDeclaration( 149 | h.map((x) => { 150 | return t.tsTypeParameter(null, null, x.node.name); 151 | }) 152 | ); 153 | } 154 | buildStatement(path: NodePath): t.Statement[] { 155 | if (path.isVariableDeclaration()) { 156 | if (path.node.kind === 'var' || path.node.kind === 'let') { 157 | throw path.buildCodeFrameError( 158 | 'cannot declare variables using let or var' 159 | ); 160 | } 161 | return path.get('declarations').map((x) => { 162 | if (t.isIdentifier(x.node.id)) { 163 | const init = x.get('init'); 164 | if (init) { 165 | return t.tSTypeAliasDeclaration( 166 | x.node.id, 167 | null, 168 | this.buildTsTypeNodeByPath(init) 169 | ); 170 | } else { 171 | throw x.buildCodeFrameError( 172 | 'variables declared with const must be initialized' 173 | ); 174 | } 175 | } else { 176 | throw x.buildCodeFrameError( 177 | `the left hand side of variable declaration should be an identifier, but ${x.node.id.type} found` 178 | ); 179 | } 180 | }); 181 | } else if (path.isTSTypeAliasDeclaration()) { 182 | return [path.node]; 183 | } else if (path.isFunctionDeclaration()) { 184 | const id = path.get('id'); 185 | if (!id.isIdentifier()) { 186 | throw path.buildCodeFrameError('only identifiers are supported'); 187 | } 188 | const param = path.get('params'); 189 | const body = path.get('body'); 190 | return [ 191 | t.tsTypeAliasDeclaration( 192 | id.node, 193 | this.buildTypeParamDeclaration(param), 194 | this.buildTsTypeNodeByPath(body) 195 | ), 196 | ]; 197 | } else { 198 | throw path.buildCodeFrameError( 199 | `Statement ${path.type} is not implemented yet` 200 | ); 201 | } 202 | } 203 | 204 | }; 205 | 206 | export default function () { 207 | let transformer = new Transformer(); 208 | const visitor: { 209 | visitor: Visitor; 210 | pre: () => void; 211 | post: () => void; 212 | } = { 213 | pre() { 214 | transformer = new Transformer(); 215 | }, 216 | visitor: { 217 | Statement(path) { 218 | const statements = transformer.buildStatement(path); 219 | path.replaceWithMultiple(statements); 220 | path.skip(); 221 | }, 222 | }, 223 | post() { 224 | 225 | }, 226 | }; 227 | return visitor; 228 | } 229 | -------------------------------------------------------------------------------- /src/modules/types/ast.d.ts: -------------------------------------------------------------------------------- 1 | import { Node } from '@babel/core'; 2 | export type ASTNode = Node; 3 | -------------------------------------------------------------------------------- /src/modules/utils/formatter.spec.ts: -------------------------------------------------------------------------------- 1 | import { formatTSCode } from './formatter'; 2 | 3 | describe('utils-formatter', () => { 4 | it('should format for TypeScript', () => { 5 | let output = formatTSCode('const a = 1;'); 6 | expect(output).toBe('const a = 1;'); 7 | output = formatTSCode(` 8 | const a = 9 | ()=>{ 10 | return 1 11 | }`); 12 | expect(output).toBe('const a = () => { return 1; };'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /src/modules/utils/formatter.ts: -------------------------------------------------------------------------------- 1 | import { generateTSCode } from './generator'; 2 | import { parseTS } from './parsing'; 3 | 4 | export function formatTSCode(input: string): string { 5 | return generateTSCode(parseTS(input)); 6 | } 7 | -------------------------------------------------------------------------------- /src/modules/utils/general.ts: -------------------------------------------------------------------------------- 1 | import { isInteger } from 'lodash'; 2 | export function repeatObject(obj: T, times: number): T[] { 3 | if (times < 0 || !isInteger(times)) { 4 | times = 0; 5 | } 6 | return Array.from({ length: times }).map((x) => obj); 7 | } 8 | -------------------------------------------------------------------------------- /src/modules/utils/generator.spec.ts: -------------------------------------------------------------------------------- 1 | describe('utils-generator', () => { 2 | it.todo('should generate ts code'); 3 | }); 4 | -------------------------------------------------------------------------------- /src/modules/utils/generator.ts: -------------------------------------------------------------------------------- 1 | import generate from '@babel/generator'; 2 | import { ASTNode } from '../types/ast'; 3 | 4 | export function generateTSCode(ast: ASTNode): string { 5 | const { code: output } = generate(ast, { 6 | concise: true, 7 | comments: false, 8 | }); 9 | return output; 10 | } 11 | -------------------------------------------------------------------------------- /src/modules/utils/parsing.spec.ts: -------------------------------------------------------------------------------- 1 | import { parseTS } from './parsing'; 2 | 3 | describe('utils-parsing', () => { 4 | it('should work for simple TypeScript code', () => { 5 | const code = parseTS('const a:number = 1; //test'); 6 | const node = code.program.body[0]; 7 | if (!node) { 8 | throw new Error('the ast node cannot be found'); 9 | } 10 | if (node.type !== 'VariableDeclaration') { 11 | throw new Error('the ast node can wrong type'); 12 | } 13 | expect(node.trailingComments?.[0]?.value).toBe('test'); 14 | }); 15 | }); 16 | -------------------------------------------------------------------------------- /src/modules/utils/parsing.ts: -------------------------------------------------------------------------------- 1 | import { parse } from '@babel/parser'; 2 | 3 | export function parseTS(code: string) { 4 | return parse(code, { 5 | plugins: [['typescript', {}]], 6 | }); 7 | } 8 | 9 | export type FileParseResult = ReturnType; 10 | -------------------------------------------------------------------------------- /src/modules/utils/typing.spec.ts: -------------------------------------------------------------------------------- 1 | import { assertNever, isNotNil } from './typing'; 2 | 3 | describe('assertNever', () => { 4 | it('should throw error when invoked', () => { 5 | const f = () => { 6 | assertNever(1 as never); 7 | }; 8 | expect(f).toThrowError(); 9 | }); 10 | }); 11 | 12 | describe('isNotNil', () => { 13 | it('should work for nullish values', () => { 14 | expect(isNotNil(null)).toBe(false); 15 | expect(isNotNil(undefined)).toBe(false); 16 | }); 17 | 18 | it('should work for falsy but not nullish values', () => { 19 | expect(isNotNil(false)).toBe(true); 20 | expect(isNotNil('')).toBe(true); 21 | expect(isNotNil(0)).toBe(true); 22 | expect(isNotNil(-0)).toBe(true); 23 | }); 24 | it('should work for truthy values', () => { 25 | expect(isNotNil(true)).toBe(true); 26 | expect(isNotNil(1)).toBe(true); 27 | expect(isNotNil('haha')).toBe(true); 28 | }); 29 | }); 30 | -------------------------------------------------------------------------------- /src/modules/utils/typing.ts: -------------------------------------------------------------------------------- 1 | export function assertNever(a: never) { 2 | throw new Error('cannot reach here'); 3 | } 4 | 5 | export function isNotNil(a: T): a is NonNullable { 6 | return a !== undefined && a !== null; 7 | } 8 | -------------------------------------------------------------------------------- /src/modules/vm/eval.d.ts: -------------------------------------------------------------------------------- 1 | import { Expect } from '@type-challenges/utils'; 2 | import { 3 | EnvConcept, 4 | Lookup, 5 | ReadOffTempValue, 6 | UpdateEnv, 7 | ValueConcept, 8 | } from './syntax/env'; 9 | import { _SampleEnv } from './syntax/loop'; 10 | import { 11 | AssignmentConcept, 12 | BinaryExprConcept, 13 | BindExprConcept, 14 | EmptyStmtConcept, 15 | ExprConcept, 16 | IdentifierConcept, 17 | IfStmtConcept, 18 | MakeIdentifier, 19 | MakeNat, 20 | MakeValueExpr, 21 | NatConcept, 22 | ValueLiteralConcept, 23 | ZERO, 24 | } from './syntax/syntax'; 25 | import { MatchCase } from './utils/helper'; 26 | import { Add, EQUALS, Lt, Lte, Sub } from './utils/nat'; 27 | 28 | // TODO: test "return" state and decided whether to stop ? 29 | export type Eval< 30 | env extends EnvConcept, 31 | expr extends ExprConcept[], 32 | > = expr extends [ 33 | infer head extends ExprConcept, 34 | ...infer tail extends ExprConcept[], 35 | ] 36 | ? Eval, tail> 37 | : env; 38 | 39 | export type EvalSingleStmt< 40 | env extends EnvConcept, 41 | expr extends ExprConcept, 42 | > = EQUALS extends true 43 | ? never 44 | : expr extends BindExprConcept 45 | ? UpdateEnv], []> 46 | : expr extends EmptyStmtConcept 47 | ? env 48 | : expr extends BinaryExprConcept 49 | ? EvalBinaryExpr 50 | : expr extends IfStmtConcept 51 | ? EvalIfStmt 52 | : expr extends ValueLiteralConcept 53 | ? UpdateEnv 54 | : expr extends IdentifierConcept 55 | ? UpdateEnv]> 56 | : expr extends AssignmentConcept 57 | ? EvalAssignment 58 | : never; 59 | 60 | type TestEvalBinaryExpr = [ 61 | Expect< 62 | EQUALS< 63 | ReadOffTempValue< 64 | EvalBinaryExpr< 65 | _SampleEnv, 66 | { 67 | kind: 'BinaryOperator'; 68 | op: '+'; 69 | left: MakeValueExpr>; 70 | right: MakeValueExpr>; 71 | } 72 | > 73 | >, 74 | MakeNat<3> 75 | > 76 | >, 77 | ]; 78 | 79 | type A = Eval< 80 | _SampleEnv, 81 | [ 82 | { 83 | kind: 'IfStmt'; 84 | test: MakeValueExpr; 85 | consequent: [MakeValueExpr>]; 86 | alternate: [MakeValueExpr>]; 87 | }, 88 | ] 89 | >; 90 | 91 | export type TestEvalSingleStmt = [ 92 | Expect< 93 | EQUALS]>>, ZERO> 94 | >, 95 | EvalSingleStmt< 96 | _SampleEnv, 97 | { 98 | kind: 'BinaryOperator'; 99 | op: '+'; 100 | left: MakeValueExpr>; 101 | right: MakeValueExpr>; 102 | } 103 | >, 104 | Expect, _SampleEnv>>, 105 | Expect< 106 | EQUALS< 107 | EvalSingleStmt< 108 | _SampleEnv, 109 | { 110 | kind: 'BinaryOperator'; 111 | op: '+'; 112 | left: MakeValueExpr>; 113 | right: MakeValueExpr>; 114 | } 115 | >, 116 | UpdateEnv<_SampleEnv, [], [MakeNat<3>]> 117 | > 118 | >, 119 | Expect< 120 | EQUALS< 121 | EvalSingleStmt< 122 | _SampleEnv, 123 | { 124 | kind: 'BinaryOperator'; 125 | op: '+'; 126 | left: MakeIdentifier<'i'>; 127 | right: MakeValueExpr>; 128 | } 129 | >, 130 | UpdateEnv<_SampleEnv, [], [MakeNat<2>]> 131 | > 132 | >, 133 | ]; 134 | 135 | type EvalBinaryExpr< 136 | env extends EnvConcept, 137 | expr extends BinaryExprConcept, 138 | __nat_literal_concept extends MakeValueExpr = MakeValueExpr, 139 | __evaluated_expr extends ValueConcept = [ 140 | expr['op'], 141 | expr['left'], 142 | expr['right'], 143 | ] extends [ 144 | infer op extends BinaryExprConcept['op'], 145 | infer __left extends ExprConcept, 146 | infer __right extends ExprConcept, 147 | ] 148 | ? [ 149 | ReadOffTempValue>, 150 | ReadOffTempValue>, 151 | ] extends [infer l extends NatConcept, infer r extends NatConcept] 152 | ? MatchCase< 153 | [ 154 | [EQUALS, Add], 155 | [EQUALS, Sub], 156 | [EQUALS, Lt], 158 | ] 159 | > 160 | : never 161 | : never, 162 | > = EvalSingleStmt>; 163 | 164 | type TestReadOffTempValue = [ 165 | Expect, MakeNat<1>>>, 166 | ]; 167 | 168 | type EvalIfStmt< 169 | env extends EnvConcept, 170 | expr extends IfStmtConcept, 171 | > = EvalSingleStmt< 172 | env, 173 | expr['test'] 174 | > extends infer __env_after_test extends EnvConcept 175 | ? ReadOffTempValue<__env_after_test> extends true 176 | ? Eval<__env_after_test, expr['consequent']> 177 | : Eval<__env_after_test, expr['alternate']> 178 | : never; 179 | 180 | type EvalAssignment< 181 | env extends EnvConcept, 182 | expr extends AssignmentConcept, 183 | > = UpdateEnv< 184 | env, 185 | [ 186 | { 187 | name: expr['left']['name']; 188 | value: ReadOffTempValue>; 189 | }, 190 | ], 191 | [] 192 | >; 193 | -------------------------------------------------------------------------------- /src/modules/vm/syntax/env.d.ts: -------------------------------------------------------------------------------- 1 | import { Expect } from '@type-challenges/utils'; 2 | import { EQUALS } from '../utils/nat'; 3 | import { MakeNat, NatConcept } from './syntax'; 4 | export type ValueConcept = NatConcept | boolean; 5 | export type Binding = { name: string; value: ValueConcept }; 6 | export type BindingStack = Binding[]; 7 | export type MakeBinding< 8 | name extends string, 9 | value extends ValueConcept, 10 | __returns extends Binding = { 11 | name: name; 12 | value: value; 13 | }, 14 | > = __returns; 15 | export type MakeEnv< 16 | T extends boolean, 17 | B extends BindingStack = [], 18 | S extends ValueConcept[] = [], 19 | __returns extends EnvConcept = { 20 | return: T; 21 | bindings: B; 22 | stack: S; 23 | }, 24 | > = __returns; 25 | export type EnvConcept = MakeEnv; 26 | 27 | export type UpdateEnv< 28 | env extends EnvConcept, 29 | bindings extends Binding[] = [], 30 | values extends ValueConcept[] = [], 31 | __returns extends EnvConcept = { 32 | bindings: [...bindings, ...env['bindings']]; 33 | return: env['return']; 34 | stack: [...values, ...env['stack']]; 35 | }, 36 | > = __returns; 37 | 38 | export type Lookup< 39 | env extends EnvConcept, 40 | name extends string, 41 | rest_variables extends BindingStack = env['bindings'], 42 | __returns extends ValueConcept = rest_variables extends [ 43 | infer head, 44 | ...infer tail extends BindingStack, 45 | ] 46 | ? head extends { name: name; value: infer value } 47 | ? value 48 | : Lookup 49 | : never, 50 | > = __returns; 51 | type _ExampleEnv = MakeEnv< 52 | false, 53 | [ 54 | { name: 'ten'; value: MakeNat<10> }, 55 | // shadowed 56 | { name: 'ten'; value: MakeNat<9> }, 57 | { name: 'one'; value: MakeNat<1> }, 58 | { name: 'zero'; value: MakeNat<0> }, 59 | ] 60 | >; 61 | 62 | type _TestLookup = [ 63 | Expect, Lookup<_ExampleEnv, 'ten'>>>, 64 | Expect, Lookup<_ExampleEnv, 'one'>>>, 65 | Expect, Lookup<_ExampleEnv, 'zero'>>>, 66 | Expect>>, 67 | ]; 68 | 69 | export type ReadOffTempValue< 70 | env extends EnvConcept, 71 | __returns extends ValueConcept = env['stack'][0], 72 | > = __returns; 73 | -------------------------------------------------------------------------------- /src/modules/vm/syntax/loop.d.ts: -------------------------------------------------------------------------------- 1 | import { Eval } from '../eval'; 2 | import { EQUALS } from '../utils/nat'; 3 | import { EnvConcept, MakeEnv } from './env'; 4 | import { EmptyStmtConcept, ExprConcept, MakeNat } from './syntax'; 5 | 6 | type TempAnonymousLoop< 7 | env extends EnvConcept, 8 | init extends ExprConcept = EmptyStmtConcept, 9 | test extends ExprConcept = EmptyStmtConcept, 10 | update extends ExprConcept = EmptyStmtConcept, 11 | body extends ExprConcept[] = [EmptyStmtConcept], 12 | __evaluated_test extends EnvConcept = Eval, 13 | __return extends EnvConcept = env, 14 | > = EQUALS extends true 15 | ? // no need to init, test first 16 | Eval extends MakeEnv< 17 | infer __should_return, 18 | infer bindings, 19 | infer stack 20 | > 21 | ? { stack: stack } 22 | : never 23 | : TempAnonymousLoop, EmptyStmtConcept, test, update, body>; 24 | 25 | type _SampleEnv = MakeEnv< 26 | false, 27 | [{ name: 'i'; value: MakeNat<0> }], 28 | [MakeNat<1>] 29 | >; 30 | type C = TempAnonymousLoop< 31 | _SampleEnv, 32 | EmptyStmtConcept, 33 | EmptyStmtConcept, 34 | EmptyStmtConcept 35 | >; 36 | 37 | // type _test = TempAnonymousLoop<{}, MakeNat<0>, LTE<>>; 38 | // function test_for() { 39 | // for (let i = 0; i < 10; i++) { 40 | // if (i * i > 5) { 41 | // if (i - 3 > 4) { 42 | // return 233; 43 | // } 44 | // break; 45 | // } else { 46 | // continue; 47 | // } 48 | // return i; 49 | // } 50 | // return 233; 51 | // } 52 | -------------------------------------------------------------------------------- /src/modules/vm/syntax/syntax.d.ts: -------------------------------------------------------------------------------- 1 | import { Expect } from '@type-challenges/utils'; 2 | import { __NatToNumericLiteralType } from '../utils/helper'; 3 | import { Add, EQUALS } from '../utils/nat'; 4 | import { ValueConcept } from './env'; 5 | 6 | export type NatConcept = number[]; 7 | export type ZERO = []; 8 | export type ONE = [1]; 9 | export type MakeNat< 10 | T extends number, 11 | res_nat extends NatConcept = [], 12 | > = T extends 0 13 | ? ZERO 14 | : T extends 1 15 | ? [1] 16 | : EQUALS> extends true 17 | ? res_nat 18 | : MakeNat>; 19 | type _ = [ 20 | Expect>, 21 | Expect, ZERO>>, 22 | Expect, [1]>>, 23 | Expect, [1, 1]>>, 24 | Expect, [1, 1, 1]>>, 25 | Expect, [1, 1, 1, 1]>>, 26 | Expect, [1, 1, 1, 1, 1]>>, 27 | Expect, [1, 1, 1, 1, 1, 1]>>, 28 | Expect, [1, 1, 1, 1, 1, 1, 1]>>, 29 | Expect, [1, 1, 1, 1, 1, 1, 1, 1]>>, 30 | Expect, [1, 1, 1, 1, 1, 1, 1, 1, 1]>>, 31 | Expect, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]>>, 32 | Expect>, 128>>, 33 | Expect>, 512>>, 34 | Expect>, 999>>, 35 | // @ts-expect-error exceeds the instantiation limit 36 | Expect>, 1000>>, 37 | ]; 38 | 39 | type SyntaxKind = ExprConcept['kind']; 40 | 41 | export type BinaryExprConcept = { 42 | kind: 'BinaryOperator'; 43 | op: '+' | '-' | '<=' | '<'; 44 | left: ExprConcept; 45 | right: ExprConcept; 46 | }; 47 | export type BindExprConcept = { 48 | kind: 'bind'; 49 | name: string; 50 | value: ValueConcept; 51 | }; 52 | 53 | export type IfStmtConcept = { 54 | kind: 'IfStmt'; 55 | test: ExprConcept; 56 | consequent: ExprConcept[]; 57 | alternate: ExprConcept[]; 58 | }; 59 | export type EmptyStmtConcept = { kind: 'empty' }; 60 | 61 | export type IdentifierConcept = { 62 | kind: 'Identifier'; 63 | name: string; 64 | }; 65 | 66 | export type MakeIdentifier = { kind: 'Identifier'; name: T }; 67 | 68 | export type ValueLiteralConcept = { 69 | kind: 'ValueLiteral'; 70 | value: ValueConcept; 71 | }; 72 | export type MakeValueExpr< 73 | T extends ValueConcept, 74 | __returns extends ValueLiteralConcept = { 75 | kind: 'ValueLiteral'; 76 | value: T; 77 | }, 78 | > = __returns; 79 | 80 | export type AssignmentConcept = { 81 | kind: 'Assignment'; 82 | left: IdentifierConcept; 83 | right: ExprConcept; 84 | }; 85 | 86 | export type ExprConcept = 87 | | AssignmentConcept 88 | | ValueLiteralConcept 89 | | IdentifierConcept 90 | | BinaryExprConcept 91 | | BindExprConcept 92 | | EmptyStmtConcept 93 | | IfStmtConcept; 94 | -------------------------------------------------------------------------------- /src/modules/vm/utils/helper.d.ts: -------------------------------------------------------------------------------- 1 | import { type Expect } from '@type-challenges/utils'; 2 | import { NatConcept } from '../syntax/syntax'; 3 | import { EQUALS } from './nat'; 4 | export type __NatToNumericLiteralType = T['length']; 5 | export type EnsureArr = T extends any[] ? T : T[]; 6 | export type _MatchBranch = [cond: boolean, result: any]; 7 | export type MatchCase = T extends [] 8 | ? never 9 | : T extends [infer head, ...infer tail extends _MatchBranch[]] 10 | ? head extends [true, infer matched_output] 11 | ? matched_output 12 | : MatchCase 13 | : never; 14 | type TestMatchCase = [ 15 | Expect, 2>>, 16 | Expect, never>>, 17 | Expect, never>>, 18 | Expect, 3>>, 19 | ]; 20 | 21 | type HEAD = T extends [infer head, ...infer rest] 22 | ? head 23 | : never; 24 | 25 | type _TestHead = [ 26 | Expect, 1>>, 27 | Expect, never>>, 28 | ]; 29 | 30 | type TAIL = T extends [infer head, ...infer rest] ? rest : []; 31 | 32 | type _TestTail = [ 33 | Expect, [2, 3]>>, 34 | Expect, []>>, 35 | ]; 36 | 37 | export type IsEmptyList< 38 | T extends any[], 39 | __returns extends boolean = EQUALS, never>, 40 | > = __returns; 41 | -------------------------------------------------------------------------------- /src/modules/vm/utils/nat.d.ts: -------------------------------------------------------------------------------- 1 | import { NatConcept } from '../syntax/syntax'; 2 | 3 | export type Add = [...A, ...B]; 4 | export type Sub = A extends [ 5 | ...B, 6 | ...infer C, 7 | ] 8 | ? C 9 | : []; 10 | export type Lte = Sub< 11 | A, 12 | B 13 | > extends [] 14 | ? true 15 | : false; 16 | 17 | export type EQUALS = (() => T extends X ? 1 : 2) extends < 18 | T, 19 | >() => T extends Y ? 1 : 2 20 | ? true 21 | : false; 22 | 23 | export type NOT = T extends true ? false : true; 24 | 25 | export type AND = A extends true 26 | ? B extends true 27 | ? true 28 | : false 29 | : false; 30 | 31 | export type OR = A extends true 32 | ? true 33 | : B extends true 34 | ? true 35 | : false; 36 | 37 | export type Lt = Lte< 38 | A, 39 | B 40 | > extends [] 41 | ? EQUALS extends false 42 | ? true 43 | : false 44 | : false; 45 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ 4 | "module": "commonjs", /* Specify what module code is generated. */ 5 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ 6 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ 7 | "strict": true, /* Enable all strict type-checking options. */ 8 | "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */ 9 | "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 10 | "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 11 | "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ 12 | "skipLibCheck": false /* Skip type checking all .d.ts files. */ 13 | } 14 | } 15 | --------------------------------------------------------------------------------