TypeScript 常见问题解决方法
类型声明文件相关
找不到模块的类型定义
问题:Cannot find module 'xxx' or its corresponding type declarations.
解决方法:
# 安装对应的类型定义文件
npm install @types/xxx --save-dev
# 或者创建自定义声明文件
# 创建 types/xxx.d.ts
declare module 'xxx' {
const content: any;
export default content;
}
扩展第三方库的类型定义
// 在项目中创建 types/index.d.ts
import 'axios';
declare module 'axios' {
export interface AxiosInstance {
request<T = any>(config: AxiosRequestConfig): Promise<T>;
get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
// ...
}
}
类型断言相关
类型断言的使用
// 方式1: as
const someValue: unknown = "this is a string";
const strLength: number = (someValue as string).length;
// 方式2: <>
const strLength: number = (<string>someValue).length;
// 方式3: !非空断言
function liveDangerously(x?: number | null) {
console.log(x!.toFixed()); // 断言x一定存在
}
配置相关
路径别名配置
// tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}
严格模式相关错误
// tsconfig.json
{
"compilerOptions": {
"strict": true,
"noImplicitAny": false, // 允许隐式的any类型
"strictNullChecks": false // 不严格检查null和undefined
}
}
常见错误处理
Object is possibly 'undefined'
// 使用可选链操作符
const value = obj?.prop?.nested;
// 使用类型守卫
if (obj && obj.prop) {
const value = obj.prop;
}
Type 'X' is not assignable to type 'Y'
// 使用类型断言
const value = someValue as ExpectedType;
// 使用类型守卫
function isExpectedType(value: any): value is ExpectedType {
return 'someProperty' in value;
}
Property 'x' does not exist on type 'Y'
// 使用接口扩展
interface ExistingType {
existingProp: string;
}
interface ExtendedType extends ExistingType {
newProp: string;
}
// 或使用类型合并
type ExtendedType = ExistingType & {
newProp: string;
};