TypeScript 严格模式在游戏开发中的价值:3251 行代码的"安全网"
在 Web 开发里,TypeScript 的 strict 模式经常被"关掉"——因为 DOM API 太复杂,类型声明经常报错。但在游戏开发
里, strict 模式是**必须的**——因为游戏逻辑是"状态机",一个类型错误会导致"玩家卡死"、"敌人消失"、"分数乱跳"。
NEON RUNNER 2077 的 tsconfig.json 里:
{
"compilerOptions": {
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "Bundler"
}
}
strict 模式挡住了什么
1. 隐式 any
// 没有 strict:可以写
function updateScore(score) { // score 是 any
return score + 10;
}
// 有 strict:必须写
function updateScore(score: number): number {
return score + 10;
}
noImplicitAny 确保每个参数都有类型。在 GameScene 里, score 、 wave 、 health 、 energy 都是 number ,不会被误用。
2. 可能为 null 的值
// 没有 strict:可以写
const keyboard = this.input.keyboard;
keyboard.on('keydown-UP', ...); // 如果 keyboard 是 null,运行时报错
// 有 strict:必须检查
const keyboard = this.input.keyboard;
if (!keyboard) return;
keyboard.on('keydown-UP', ...);
strictNullChecks 确保 this.input.keyboard 可能为 null 时,必须先检查再使用。 MenuScene 里的 setupInput() 就是
这么写的。
3. 未使用的变量
// 没有 unused:可以写
onUpdate: (_tween, _key, _target, current) => { ... }
// 有 unused:必须用下划线前缀
onUpdate: (_tween: Phaser.Tweens.Tween, _key: string, _target: unknown, current: number) => { ... }
noUnusedLocals 和 noUnusedParameters 确保未使用的变量必须用 _ 前缀。 PreloadScene 里的 onUpdate 回调就是这么
写的。
- 点赞
- 收藏
- 关注作者
评论(0)