一、获取对象中的value报错
代码示例
报错信息
解决方法
定义CardClassObj interface 类型, 获取值使用 cardClassObj[arr[0] as keyof typeof cardClassObj];
const getCardClassName = (detailInfo: DetailInfo, obj: Obj) => {
const { Status } = detailInfo;
interface CardClassObj {
Alert: {
className: string,
name: string,
},
Unhealthy: {
className: string,
name: string,
},
Healthy:{
className: string,
name: string,
},
Inactive: {
className: string,
name: string,
},
Active: {
className: string,
name: string,
},
Unknown: {
className: string,
name: string,
},
}
const cardClassObj: CardClassObj = {
Alert: {
className: 'status redState',
name: obj.alert,
},
Unhealthy: {
className: 'status orangeState',
name: obj.unhealthy,
},
Healthy: {
className: 'status greenState',
name: obj.healthy,
},
Inactive: {
className: 'status redState',
name: obj.inactive,
},
Active: {
className: 'status greenState',
name: obj.active,
},
Unknown: {
className: 'status grayState',
name: obj.unknown,
},
};
const cardClassObjKeys = Object.keys(cardClassObj);
const arr = cardClassObjKeys.filter((item) => Status === item);
if (arr.length > 0) {
return cardClassObj[arr[0]as keyof typeof cardClassObj];
}
return cardClassObj.Unknown;
}
二、 定义默认值报错
代码示例
报错信息
Property ‘deviceId’ does not exist on type ‘never’.
解决办法
默认值修改为 [ ] as any[ ]
const [newList, setNewList] = useState([] as any[]);
三、父子组件传参定义报错
代码示例
报错信息
(property) openFlag: boolean
Type ‘{ openFlag: boolean; updateOpenFlag: Dispatch<SetStateAction>; }’ is not assignable to type ‘IntrinsicAttributes & Omit<WrappedComponentProps<“intl”>, “intl”> & { forwardedRef?: Ref | undefined; }’.
Property ‘openFlag’ does not exist on type ‘IntrinsicAttributes & Omit<WrappedComponentProps<“intl”>, “intl”> & { forwardedRef?: Ref | undefined; }’.ts(2322)
解决办法
在子组件中定义interface 接口参数类型
子组件
四、绑定click 事件报错
代码示例
报错信息
Type ‘void’ is not assignable to type ‘MouseEventHandler | undefined’.ts(2322)
index.d.ts(1479, 9): The expected type comes from property ‘onClick’ which is declared here on type ‘DetailedHTMLProps<HTMLAttributes, HTMLDivElement>’
解决办法
点击事件变为箭头函数的格式
五、全局没有定义类型报错
报错信息
Property ‘REDUX_DEVTOOLS_EXTENSION_COMPOSE’ does not exist on type ‘Window & typeof globalThis’.
解决办法
你可以创建一个文件 src/types/global.d.ts
export {};
declare global {
interface Window {
__REDUX_DEVTOOLS_EXTENSION_COMPOSE__: Function;
}
}
然后在 tsconfig.json 文件中确认有下面的命令
"include": [
"src/**/*"
]