【问题标题】:Typescript definition for ES6 mixinsES6 mixin 的打字稿定义
【发布时间】:2023-04-02 06:18:01
【问题描述】:

有没有办法为ES6 mix-in 编写 Typescript 定义?

我在library.js 中有这个模式,我想创建library.d.ts

// declaration in `library.js`
class Super extends Simple {
    constructor() {}

    static Compose(Base = Super) {
        return class extends Base {
            // ...    
        }

    }
}

// usage in `client.js`
class MyClass extends Super.Compose() {}
let myInstance = new MyClass();

class MyOtherClass extends Super.Compose(AnotherClass) {}

【问题讨论】:

    标签: javascript typescript ecmascript-6


    【解决方案1】:

    不,Typescript 类型系统的表达能力不够 - 请参阅 https://github.com/Microsoft/TypeScript/issues/7225https://github.com/Microsoft/TypeScript/issues/4890 中的讨论。

    打字稿中惯用的“类类型”写成

    interface Constructor<T> {
        new (...args): T;
    }
    

    所以编写 Compose 声明的一种方法是

    export declare class Simple {}
    
    export declare class Super extends Simple {
        static Compose<T>(Base?: Constructor<T>): Constructor<T & {/*mixed-in declarations*/}>
    }
    

    也就是说,Compose 返回类型被声明为交集类型的构造函数——该类型必须具有参数 (Base) 的所有属性以及 mixin 的所有属性。

    您可以像这样使用该声明(假设它在 library.d.ts 文件中)

    import {Super} from './library'
    
    let MyComposed = Super.Compose(Super)
    let myInstance = new MyComposed
    

    轻微的不便是您总是必须为 Super.Compose() 提供参数,因为类型推断在不知道默认参数的值的情况下不起作用,并且您无法在声明文件中为默认参数提供值。

    但最大的问题是你不能真正将 Compose 的结果用作一个类:

    class MyClass extends Super.Compose(Super) {}
    

    由于上述问题无法编译:

    error TS2509: Base constructor return type 'Super & {}' is not a class or interface type.
    

    【讨论】:

    猜你喜欢
    • 2020-08-30
    • 2018-05-01
    • 2015-07-13
    • 1970-01-01
    • 2014-11-16
    • 2013-03-20
    • 1970-01-01
    • 2018-06-05
    • 2015-10-06
    相关资源
    最近更新 更多