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

TypeScript编写第三方库声明时如何让构造函数返回指定实例类型

解决方案

你原来的写法不生效是因为 declare class 默认会将 new 调用的返回值绑定为该类本身的实例类型,类内部定义的构造签名无法覆盖这个默认行为。可以将构造函数的声明拆分,用接口定义构造签名的方式实现需求,正确写法如下:

// 定义构造函数的类型,指定new调用的返回值类型
interface PexRTCConstructor {
  new(): PexRTC.PexipInstance;
  // 如果PexRTC有静态属性/方法,直接在这里补充定义即可
  // 例如 staticVersion: string;
}

// 声明全局的PexRTC符合上述构造函数类型
declare const PexRTC: PexRTCConstructor;

declare namespace PexRTC {
    export interface PexipInstance {
        foo: true;
    }
}

// 此时instance的类型就是PexRTC.PexipInstance
const instance = new PexRTC();

补充说明

如果该第三方库的构造函数支持传参,只需要修改PexRTCConstructor里的构造签名即可,比如:

interface PexRTCConstructor {
  new(opts: { server: string }): PexRTC.PexipInstance;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 23:45:05