initial commit
This commit is contained in:
95
TYPESCRIPT_WARNINGS_FIXES.md
Normal file
95
TYPESCRIPT_WARNINGS_FIXES.md
Normal file
@@ -0,0 +1,95 @@
|
||||
# TypeScript 警告修复说明
|
||||
|
||||
## 修复的问题
|
||||
|
||||
### 1. ✅ 已修复:`Property 'CodeHighlight' may not exist on type 'Window'`
|
||||
**问题原因:** TypeScript 不知道 `window.CodeHighlight` 这个自定义属性的存在。
|
||||
|
||||
**解决方案:**
|
||||
- 创建了 `src/types/global.d.ts` 文件来扩展 Window 接口
|
||||
- 添加了全局类型声明支持自定义属性
|
||||
|
||||
### 2. ⚠️ 残留警告:`document.execCommand('copy') is deprecated`
|
||||
**问题原因:** `document.execCommand` 是已废弃的 API。
|
||||
|
||||
**现状:**
|
||||
- 已优化为优先使用现代的 `navigator.clipboard` API
|
||||
- 只在不支持 Clipboard API 的环境中降级使用 `execCommand`
|
||||
- 这是向后兼容的必要措施,警告可以忽略
|
||||
|
||||
**代码实现:**
|
||||
```javascript
|
||||
// 优先使用现代 API
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} else {
|
||||
// 降级到传统方法(会有警告但功能正常)
|
||||
document.execCommand('copy');
|
||||
}
|
||||
```
|
||||
|
||||
### 3. ✅ 已修复:`'line' is declared but its value is never read`
|
||||
**问题原因:** forEach 回调中的 `line` 参数未被使用。
|
||||
|
||||
**解决方案:** 将未使用的参数重命名为 `_`
|
||||
```javascript
|
||||
// 修复前
|
||||
lines.forEach((line, index) => {
|
||||
// line 未被使用
|
||||
});
|
||||
|
||||
// 修复后
|
||||
lines.forEach((_, index) => {
|
||||
// 使用 _ 表示未使用的参数
|
||||
});
|
||||
```
|
||||
|
||||
### 4. ✅ 已修复:`'nav' is declared but its value is never read`
|
||||
**问题原因:** 获取了 DOM 元素但未使用。
|
||||
|
||||
**解决方案:** 删除了未使用的变量声明
|
||||
|
||||
### 5. ✅ 已修复:`'navigationItems' is declared but its value is never read`
|
||||
**问题原因:** Props 中定义了但未在组件中使用。
|
||||
|
||||
**解决方案:** 从 Props 解构中移除未使用的属性
|
||||
|
||||
### 6. ✅ 已修复:`Math.random().toString(36).substr(2, 9)` - substr is deprecated
|
||||
**问题原因:** `substr` 方法已被废弃。
|
||||
|
||||
**解决方案:** 替换为现代的 `substring` 方法
|
||||
```javascript
|
||||
// 修复前
|
||||
Math.random().toString(36).substr(2, 9)
|
||||
|
||||
// 修复后
|
||||
Math.random().toString(36).substring(2, 11)
|
||||
```
|
||||
|
||||
## 构建结果
|
||||
|
||||
现在的构建输出:
|
||||
- ✅ **0 错误**
|
||||
- ⚠️ **1 个警告**(`execCommand` 废弃警告 - 可安全忽略)
|
||||
- 💡 **3 个提示**(来自其他文件的轻微问题)
|
||||
|
||||
## 关于剩余警告的说明
|
||||
|
||||
最后剩余的 `document.execCommand` 警告是预期的,因为:
|
||||
|
||||
1. **兼容性需求**:需要支持旧版浏览器
|
||||
2. **安全限制**:Clipboard API 只在 HTTPS 环境下工作
|
||||
3. **降级策略**:这是一个合理的 progressive enhancement 实现
|
||||
|
||||
如果你希望完全消除这个警告,可以:
|
||||
- 使用 `// @ts-ignore` 注释
|
||||
- 或者移除降级支持(但会影响旧浏览器兼容性)
|
||||
|
||||
## 最佳实践
|
||||
|
||||
1. **类型安全**:为所有自定义全局变量创建类型声明
|
||||
2. **现代 API**:优先使用新的 Web API,适当降级
|
||||
3. **未使用变量**:使用 `_` 前缀或直接删除
|
||||
4. **废弃方法**:及时更新到推荐的替代方案
|
||||
|
||||
项目现在拥有更好的 TypeScript 类型安全性和更少的警告!
|
||||
Reference in New Issue
Block a user