最佳实践
函数
函数根据函数参数类型返回不同类型
普通函数
- 使用函数重载;
function add(param: number): number;
function add(param: string): string;
function add(param: string | number): string | number {
if (typeof param === "string") {
return param;
}
return param;
}
箭头函数
- 使用 interface + as 操作符;
interface IAdd {
(param: number): number;
(param: string): string;
}
const add = ((param: string | number) => {
if (typeof param === "string") {
return param;
}
return param;
}) as IAdd;
函数根据函数参数值返回不同类型
普通函数
- 使用函数重载;
- 同函数根据函数参数类型返回不同类型;
箭头函数
- 使用 interface + as 操作符;
- 同函数根据函数参数类型返回不同类型;
普通函数和箭头函数适用
- interface + 映射类型;
interface IAdd {
1: number;
2: string;
}
function sub<T extends keyof IAdd>(param: T) {
return {
1: 3,
2: "",
}[param];
}
自定义工具类型
Diff
Diff<T,U>
;- 从 T 中移除 U 包含的类型;
type Diff<T, U> = T extends U ? never : T;
Intersect
Intersect<T,U>
;- 获得 T 和 U 共有类型,生成新类型;
type Intersect<T, U> = Pick<
T,
Extract<keyof T, keyof U> & Extract<keyof U, keyof T>
>;
type 和 interface 的区别
- 优先使用 interface;
interface | type | |
---|---|---|
声明对象 | 对象, 类 | interface, 联合类型, 交叉类型, 元组类型 |
合并性 | 多次声明同名 interface, 自动合并 | 多次什么同名 type, 报错 |
约束和继承 | interface 可约束对象/对象/函数, 可以继承和被继承 | 无法约束和继承 |
物理存在 | interface 实际存在 | type 只是若干类型的别名, 无实际存在 |
配置文件
调试
vscode
- 安装 tsx;
- 配置 launch.json;
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "core",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/tsx",
"program": "${file}",
"cwd": "${fileDirname}",
"internalConsoleOptions": "openOnSessionStart",
"skipFiles": ["<node_internals>/**", "node_modules/**"]
},
{
"type": "node",
"request": "launch",
"name": "Debug Current Test File",
"autoAttachChildProcesses": true,
"skipFiles": ["<node_internals>/**", "**/node_modules/**"],
"program": "${workspaceRoot}/node_modules/vitest/vitest.mjs",
"args": ["run", "${relativeFile}"],
"smartStep": true,
"console": "integratedTerminal"
}
]
}