JS TS - Serbipunk/notes GitHub Wiki

https://webpack.js.org/

interactive tool

npx tsx

package.json

The ^ symbol is called a caret (pronounced "KAIR-it").

In npm/package.json version strings, it means "compatible with this version" — specifically, it allows updates to the minor and patch versions, but locks the major version.

So ^1.14.0 means: accept any version >=1.14.0 and <2.0.0.

The three parts of a version are MAJOR.MINOR.PATCH:

^1.14.0 → can update to 1.15.0, 1.99.9, but NOT 2.0.0
~1.14.0 (tilde) → only patch updates: >=1.14.0 and <1.15.0
1.14.0 (no symbol) → exact version only

variable initialisation

  • var : function-scoped (global object will polutes window, not recommended)
  • let / const : block-scoped

JS built in 8 data types:

boolean
string
number
bigint
symbol
object
undefined
null

class constructor

class User {
  constructor(name) {
    this.name = name;
  }
}

const u1 = new User("Alice");  // ✅ 正确
const u2 = User("Alice");       // ❌ TypeError: Class constructor User cannot be invoked without 'new'

never

never 类型的一个重要特点是,可以赋值给任意其他类型

let x: never;
let y: string = x; // ✅ OK

Q 所以现在typescript用来做js的接口封装是常见做法咯? A 是的,非常常见,而且有两种场景:

  1. 库作者自己写(比如 drei 这里) 库用 TypeScript 写,发布时同时输出 .js(运行)和 .d.ts(类型),用户 import 时自动获得类型提示。

  2. 社区补写(针对纯 JS 的老库) 有些库本身是纯 JavaScript 写的,没有类型。社区会单独维护一个 @types/xxx 包,专门只包含 .d.ts 文件。比如:

npm install lodash # 纯 JS,没有类型 npm install @types/lodash # 社区补的类型声明 所以现在 JS 生态里基本是:

新库 → 直接用 TypeScript 写,自动生成 .d.ts 老库 → 靠 @types/ 补类型 你项目里用的 @react-three/drei 就是第一种,TypeScript 写的,.d.ts 是构建时自动生成的。

Q好的,有用ts写实现的么?

A有,而且现在大多数现代库都是直接用 TypeScript 写实现的。

drei 本身就是,你可以看它的源码:

知识卡片:TypeScript + React 类型基础


卡片 1 — interface 是 TypeScript 专属

  • JavaScript 没有 interface,它是 TypeScript 的静态类型工具
  • 编译成 JS 后完全消失,零运行时开销
  • 作用:描述对象的"形状"(有哪些属性、什么类型)
  • 需要显式 export,不会自动导出

卡片 2 — interface vs class

interface class
编译后存在 ✗ 消失 ✓ 保留
能实例化
能写方法实现 ✗ 只能声明
适合场景 描述数据结构 有行为的对象蓝图

卡片 3 — React.FC<> 的使用建议

  • React.FC<Props> = "这是一个 React 函数组件,props 类型是 Props"
  • 历史问题:React 17 及之前隐式包含 children,导致类型不严谨
  • 现代推荐:省略 React.FC,直接在参数上标注类型
// 旧写法
const Comp: React.FC<Props> = ({ name }) => ...

// 现代推荐
const Comp = ({ name }: Props) => ...

卡片 4 — interfaceReact.FC 的关系

两者是配合关系,不是包含关系:

interface CardMeshProps {   // ① 定义 props 的形状
  toggles: TextureToggles;
}

const CardMesh: React.FC<CardMeshProps> = ({ toggles }) => {
//              ↑ 函数类型     ↑ props 类型来自 interface
  • interface 负责描述"输入长什么样"
  • React.FC<> 负责描述"这个函数是个组件"
  • <CardMeshProps> 是泛型,把两者连接起来
⚠️ **GitHub.com Fallback** ⚠️