1. Type ‘number | null’ is not assignable to type ‘number | undefined’.


问题描述:
sqlPort的类型是 number | null
el-input-number 组件声明的传值类型是 number | undefined,sqlPort声明断言的是 number | null,两者不匹配所以报错。
解决方法:
方式一、将<el-input-number> 改为<el-input>,注意输入类型的校验问题
方式二、将 sqlInfo的类型定义为 number | undefined, 初始化时赋值 undefined

注:可以使用 pnpm ts:check 做一下严格的类型检查
……
2. 动态生成多个表单的类型定义
const sqlProtocolsForm = reactive<Record<string, FormInstance>>({});
3. 类型“EventTarget”上不存在属性“value”。

问题描述:
e.target 默认为 HTMLElement类型,不能确保一定有value属性。需要断言成HTMLInputElement类型
注:
style 是HTMLElement类型
const nodeElement = document.getElementsByClassName('g6-component-tooltip');
(nodeElement[0] as HTMLElement).style.display = 'none';
解决方法:

或者

function Func(e: Event) {
const val = (e.target as HTMLInputElement).value;
}
4.元素隐式具有 “any” 类型,因为类型为 “string” 的表达式不能用于索引类型 “xxx”。
问题复现(情况一):


解决方法:
1.直接进行类型断言

或者

2.字段扩展声明
// 为需要被遍历的对象声明一个接口,用以确定键值的数据类型
interface SearchKeyType {
[key: string]: string | number ; // 字段扩展声明
}
示例1:

示例2:

3.定义一个函数:isValidKey(), 使用keyof在用到的地方进行判断
a.在通用文件中定义一个判断函数,例如 util.ts文件:
// 定义isValidKey()
export function isValidKey(
key: string | number | symbol,
object: object,
): key is keyof typeof object {
return key in object;
}
b.在用到的地方进行判断:
for (const key in obejct) {
if(isValidKey(key,obejct)){
// 处理...
obejct[key]
....
}
}
例如:
import { isValidKey } from '@/utils/util';
Object.keys(commandOption).map((item) => {
if (isValidKey(item, commandOption)) {
optionArr.push({
value: commandOption[item],
key: item,
showTooltip: false,
});
}
});
问题复现(情况二):
obj[item] = 值;

解决方法:
1. 直接进行类型断言
item 类型断言为keyof typeof obj 无效;
obj类型断言为any;
(obj as any)[item] = 值;
2.继承自定义接口
如下图:


文章讲述了在使用TypeScript时遇到的一些类型匹配问题,如number|null与number|undefined的不兼容,动态表单类型定义,事件处理中target.value的类型安全访问,以及对象索引的类型错误。提供了解决这些问题的方法,包括更改组件类型,调整类型定义,类型断言和使用isValidKey函数进行安全性检查。
6万+

被折叠的 条评论
为什么被折叠?



