You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Instascan库声明适配TypeScript的类型定义?

TypeScript项目Instascan库类型声明解决方案

导致你的声明不生效的核心原因通常为模块名大小写不匹配、tsconfig未识别声明文件,按以下步骤调整即可:

1. 调整tsconfig配置

确保你的tsconfig.json的include字段包含.d.ts文件,让TS可以识别到你写的类型声明:

{
  "compilerOptions": {
    // 你的其他配置项
  },
  "include": [
    "src/**/*",
    "*.d.ts" // 新增这行,识别根目录下的index.d.ts
  ]
}

2. 修正模块声明内容

模块名需要和你安装的包名、import时的包名完全匹配,绝大多数情况下npm安装的Instascan包名是全小写instascan,不要写大写的Instascan,完整声明示例如下:

// /index.d.ts
declare module "instascan" {
  export class Camera {
    static getCameras(): Promise<Camera[]>;
    id: string;
    name: string;
    constructor(id: string, name: string);
  }

  export class Scanner {
    constructor(options?: {
      video?: HTMLVideoElement;
      mirror?: boolean;
      backgroundScan?: boolean;
      refractoryPeriod?: number;
      scanPeriod?: number;
    });
    start(camera: Camera): void;
    stop(): void;
    on(event: 'scan', listener: (content: string) => void): void;
    on(event: 'active' | 'inactive', listener: () => void): void;
  }
}

3. 调整导入语句

和模块声明的包名保持一致即可:

// /main.ts
import { Camera, Scanner } from "instascan";

// 后续业务代码

如果是通过CDN直接引入全局Instascan对象,不需要import,额外添加全局类型声明即可:

// 在index.d.ts中追加以下内容
declare global {
  interface Window {
    Instascan: typeof import('instascan')
  }
}

内容的提问来源于stack exchange,提问作者Axtlan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 23:27:03