在打字稿中与私有字段混合

问题描述 投票:0回答:1

是否可以在 mixins 中使用私有字段?我想在内部保留一个字段,但 TS 编译器说 mixins 只能有 protected 或 private 字段。

ChatGPT 建议使用地图,这意味着每次我想使用该字段时都要查找。

type Constructor<T = {}> = new (...args: any[]) => T;

class BaseClass {
    name = "BaseClass";
}

function ExampleMixin<TBase extends Constructor>(Base: TBase) {
    return class extends Base {
        private secret: string = "This is private"; // Private field causing the export issue

        getSecret() {
            return this.secret;
        }
    };
}

// Attempt to export the mixin function
export const MixedClass = ExampleMixin(BaseClass);
typescript mixins
1个回答
0
投票

如果您不想从 mixin 中公开任何内容,只需指定一个显式返回值(混合类是唯一的公共 API):

type Constructor<T = {}> = new (...args: any[]) => T;

class BaseClass {
    name = "BaseClass";
}

//returns TBase
function ExampleMixin<TBase extends Constructor>(Base: TBase): TBase {
    return class extends Base {
        private secret: string = "This is private";

        getSecret() {
            return this.secret;
        }
    };
}

export const MixedClass = ExampleMixin(BaseClass);

如果你想从mixin中暴露部分API,定义一个接口并告诉返回值是类和接口的组合:

export interface PartialInterface
{
    publicProp: string;
}

function ExampleMixin<TBase extends Constructor>(Base: TBase): Constructor<PartialInterface> & TBase {
    return class extends Base {
        private secret: string = "This is private"; 
        publicProp = "hello";
        getSecret() {
            return this.secret;
        }
    };
}

export const MixedClass = ExampleMixin(BaseClass);
© www.soinside.com 2019 - 2024. All rights reserved.