TypeScript mixin扩展了其他mixin:不一致"冲突的声明"错误

时间:2018-03-23 20:43:19

标签: typescript mixins typescript2.8

我想写两个mixin类FooBarBar需要访问Foo的受保护接口。因此,我使用TS2.8条件类型来提取Foo类的类型,并将此类型用作Bar mixin的Base类的通用约束。

不幸的是,这会导致神秘的不一致"冲突的声明"错误。为什么?这是TS错误吗?我可以解决它吗?

/*
* Why is this type error happening?
*   Class 'Composed' incorrectly extends base class 'Bar...
*     Type 'Composed' is not assignable to type 'Bar...
*       Property '_referenceToEmptyInterface' has conflicting declarations and is inaccessible in type 'Composed'.
*/
class Composed extends BarMixin(FooMixin(EventEmitter)) {}

import { EventEmitter } from "events";
type Constructor<I = {}> = new (...args: any[]) => I;

interface EmptyInterface {}

/** Mixin */
function FooMixin<C extends Constructor>(Base: C) {
    return class extends Base {
        private _referenceToEmptyInterface: EmptyInterface = {}; // Causes the error.  Why?
        private _fooPrivate: number = 0; // Does not cause an error.  Why not, given the above?
        protected _fooProtected: number = 0;
    }
}

/** Type of class that creates instances of type Foo */
type FooConstructor = typeof FooMixin extends (a: Constructor) => infer Cls ? Cls : never;

/** Mixin that can only extend subclasses of Foo */
function BarMixin<C extends FooConstructor>(Base: C) {
    return class extends Base {
        barMethod() {
            // We require `Base` to implement `Foo` because we need access to protected `Foo` properties.
            this._fooProtected++;
        }
    }
}

_referenceToEmptyInterface被标记为重复声明。但是,_fooPrivate不是。唯一的区别是前者的类型是指接口声明,而后者的类型是原语。接口声明完全为空,并在mixin函数之外声明,因此_referenceToEmptyInterface的所有声明都应该相同。

这是编译器中的错误吗?我应该如何处理这种情况?

编辑:相关GH问题:https://github.com/Microsoft/TypeScript/issues/22845

0 个答案:

没有答案