使用 typescript 时修改 npm 包的类型定义

使用 typescript 时修改 npm 包的类型定义

出现的场景

某些 npm 包的类型定义可能有误. 此时需要修改该定义.
如npm 包 @tarojs/components 中的 Text 组件的属性定义中缺少小程序官方的 userSelect 属性.

该组件缺少属性 userSelect

image.png

在小程序官方组件中支持 user-select 属性

image.png

此时在使用该组件的时候会报错, 找不到该属性

image.png

解决方法

第一步: 在本地增加该模块的类型定义文件

新建文件 src/types/@tarojs/components/index.d.ts

重新定义组件 Text 的类型

import { ComponentType } from 'react';
import type { TextProps as LibTextProps } from '../../../../node_modules/@tarojs/components/types/Text';

// 导出原 npm 包中的所有组件
export * from '../../../../node_modules/@tarojs/components/types/index';

interface TextProps extends LibTextProps {
  /** 增加新的属性的定义 */
  userSelect?: boolean;
}

// 导出自定义的 Text 组件
export const Text: ComponentType<Text.TextProps>;
复制代码

image.png

第二步: 修改tsconfig配置

  1. 修改该模块的解析路径

在 tsconfig.json 中的 paths 属性中, 指定该 npm 包的解析路径为自定义的该包的类型文件

// 文件 tsconfig.json 
{
  "compilerOptions": {
    "paths": {
      "@tarojs/components": ["src/types/@tarojs/components"]
    }
  }
}
复制代码

结果:

image.png
此时在使用该组件时, 可以正确解析到自定义的类型

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享