从 C、Python 等传统语言走过来的对类型都有“深刻”的理解,去掉枚举、列表、元祖、集合等组合型的,基础类型我整理了下表:
类型 | C | Python | Go | typescript |
---|---|---|---|---|
整数 | int short long | int long | int[x] uint[x] rune | number |
浮点数 | float double | float | float32 float64 | number |
复数 | _complex | complex | complex64 complex128 | number |
字符 | char | byte | ||
字符串 | str unicode | string | string | |
布尔 | _bool | boolean | bool | boolean |
指针 | * | uintptr | ||
任意类型 | any unknown | |||
无类型 | void | NoneType | void never | |
特色类型 | 字面量类型 |
ts 比其他语言在某些方面好像简化了,比如用 number 代替各种数字型,但某些方面又好像复杂了很多,任意类型和无类型就弄出来 4 种,还搞出来 字面量类型 —— 这些变化,体现了 ts 语言设计者的权衡和用心,同时语言设计者也为用户扩展 ts 的 type 留下了一些语法,更是在 type 自定义、扩展这个方面与其他语言拉开了差异。
下面,从我一个刚入门不久的 ts 用户经历和感受,聊聊我最近对 TypeScript 中 Type 这几个字的理解。