TypeScript 严格模式在游戏开发中的价值:3251 行代码的"安全网"

举报
yd_296221794 发表于 2026/10/10 10:51:51 2026/10/10
【摘要】 在 Web 开发里,TypeScript 的 strict 模式经常被"关掉"——因为 DOM API 太复杂,类型声明经常报错。但在游戏开发里, strict 模式是**必须的**——因为游戏逻辑是"状态机",一个类型错误会导致"玩家卡死"、"敌人消失"、"分数乱跳"。NEON RUNNER 2077 的 tsconfig.json 里:{"compilerOptions": {"stri...

在 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 回调就是这么
写的。

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0)

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。