TS7053: 元素隐式具有 "any" 类型,因为类型为 "string" 的表达式不能用于索引类型 "{ doc_image: string; docx: string[]; }"。ts(7053)
const MINE_TYPES = {
doc_image: ['image/png', 'image/gif', 'image/jpeg', 'image/jpg', 'image/bmp'].join(','),
// 暂仅支持docx和xlsx
docx: [
// 'application/pdf',
// 'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
]
};
- ts对于传入的apiType,编译器只知道为字符串而不是具体的doc_image或者docx,所以需要自行使用断言以及显示声明传入的值与这些值一致。
const accept = MINE_TYPES[apiType as keyof typeof MINE_TYPES] || '*';
TS2531: Type ‘HTMLElement | null‘ is not assignable to type ‘HTMLElement‘
- 查找DOM这块,很有可能是找不到该DOM元素的,如下:
很确定dom层一渲染dom树,使用断言
// 点击按钮,返回顶部
const handleBackToTop = () => {
let page_content: HTMLElement = document.getElementById('file-page-content') as HTMLElement;
if (page_content !== null) {
page_content.scrollTop = 0;
}
};
TS2345: Typescript 'string | 类型的参数null' 不能分配给“字符串”类型的参数.类型 'null' 不能分配给类型 'string'
const authorInfo = localStorage.getItem('LOGIN_USER')
? JSON.parse(localStorage.getItem('LOGIN_USER') as string)
: null;
TS2307: 【找不到模块】或【ts导入js文件】
可以归为一类问题,都是导入非ts模块 而报错,而ts的编译是需要有声明类型的
这类报错一般有如下两种情况:
- import导入依赖包,但是提示找不到该包
- ts文件中导入js文件
原因:
- 依赖包没有做ts化,没有声明文件,或者说暴露出来的接口,import不支持
- ts不能导入js,除非做一些配置文件的相关配置(但是尽量不要在ts项目存在js项目)
解决:
- 国际化网站下载下来的是js文件,但是vite项目不能使用require来导入外部文件
vite无法使用require的替代方案 - 古墩古墩 - 博客园,api已废弃
- 解决方法1:(无伤解决方法)类似声明非ts项目依赖一样,单独声明再使用(在ts中怎么引入js文件 - 冰中焱 - 博客园)
en.d.ts中添加
···
declare module '@/i18n/lang/zh.js';
declare module '@/i18n/lang/en.js';
···
然后再ts文件中直接导入使用即可
import zh from '@/i18n/lang/zh.js';
import en from '@/i18n/lang/en.js';
···
- 解决方法2:直接在tsconfig中配置可以使用js的配置项,但是需要单独添加ts编译后的js目录,改动较大
TS2339: Property 'replaceAll' does not exist on type 'string'
- ts不能使用js中String的内置API:replaceAll方法
- 使用其他字符串api来达到该目的,https://stackoverflow.com/questions/63616486/property-replaceall-does-not-exist-on-type-string,不推荐使用该方法
- 解决方法:默认 TypeScript 不支持某些 es6 polyfill 函数,在tsconfig.json配置中进行配置新版本的js语法
{
...,
"compilerOptions": {
...,
"lib": [
...,
"ES2021.String"
]
}
}
TS2589: Type instantiation is excessively deep and possibly infinite.
- 如果使用js文件导入,那么在ts文件中使用就会报ts 2589错误。
src/utils/fetch.ts:63:55 - error TS2589: Type instantiation is excessively deep and possibly infinite.
63 message[response.config.warnType as NoticeType](i18n.global.t(msg));
使用如下方式导入js导出来的js和json数据
import { createI18n } from 'vue-i18n';
import config from './config.json';
import zh from '@/i18n/lang/zh.js';
import en from '@/i18n/lang/en.js';
import { ref } from 'vue';
let zh_obj = {};
zh_obj = zh;
let en_obj = {};
en_obj = en;
export const lang = ref('zh_obj');
export const languages = config;
const i18n = createI18n({
locale: lang.value,
fallbackLocale: lang.value,
messages: {
zh_obj,
en_obj
}
});
export default i18n;
评论区