打字稿:无法导出通用接口模块并包含其他通用接口

 化妆师苹苹 发布于 2023-02-04 19:47

我正在尝试为Bluebird编写一个CommonJS声明文件,这是一个直接导出通用Promise类的promise库.但是,该库还将几个其他泛型类导出为静态成员(PromiseInspection),并且似乎无法使用typescript对其进行建模.

编辑:用法示例,用于说明模块的导出类的工作方式:

import Promise = require('bluebird');
var promise:Promise = Promise.cast(5);
var x:Promise.PromiseInspection = promise.inspect();

我尝试了几种策略 - 简化示例如下:

1.显而易见的方式

declare module "bluebird" {
    class PromiseInspection {
        // ...
    }
    class Promise {
        PromiseInspection: typeof PromiseInspection; // error
        constructor();
        inspect():PromiseInspection; // error
        static cast(value:U):Promise; 
        // ...
    }
    export = Promise;
}

失败,错误无法使用私有类型PromiseInspection作为公共属性

2.使用静态接口

declare module "bluebird2" {
    interface PromiseInspection {
        // ...  
    }
    interface Promise {
        constructor();
        inspect():PromiseInspection;
    }
    interface PromiseStatic {
        new();
        PromiseInspection:typeof PromiseInspection;
        cast(value:U):Promise; // error
    }
    export = PromiseStatic;
}

同样失败,但这次私有类型是Promise

3.尝试从模块直接导出构造函数

declare module "bluebird3" {
    export interface PromiseInspection {
        // ...
    }
    export interface Promise {
        constructor();
        inspect():PromiseInspection;
    }

    export new(); // syntax error
    export function cast(value:U):Promise; 
}

这几乎可以工作,当然除了这样的构造函数不可能.

4.命名空间污染方式(Works,有缺点)

interface PromiseInspection {
    // ...
}
interface Promise {
    constructor();
    inspect():PromiseInspection;
}

declare module "bluebird4" {    
    interface PromiseStatic {
        new():Promise;
        PromiseInspection: typeof PromiseInspection;
        cast(value:U):Promise;
    }
    export = PromiseStatic;
}

Works,但它使用Promise和PromiseInspection污染全局命名空间.这可能没问题,但我宁愿避免使用它,因为在CommonJS中它通常被认为是不可接受的.

5.声明合并(让我90%的方式...)

declare module "bluebird5" {
    module Promise {
        export interface PromiseInspection {
            value(): T;
            // ...
        }
        export
        function cast(value: U): Promise ;
    }

    class Promise {
        new  (): Promise  ;
        inspect(): Promise.PromiseInspection  ;
    }

    export = Promise;
}

几乎没有-除了我现在不能代替class Promiseinterface Promise,使Promiseunextendable.如果我尝试这样做,请使用以下代码:

import Promise = require('bluebird');
var x = new Promise();
x.inspect().value().toExponential();

失败并显示错误"无效'新'表达式"

链接到实际的,正在进行中的bluebird.d.ts - 这个当前污染全局命名空间(使用解决方案4)

有没有更好的方法来做到这一点,还是我遇到了语言限制?

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有