在 Mixin 中继承父 class 属性

Inheriting parent class attributes in Mixin

我正在尝试从 mixin

中继承的 class 访问 属性
class BaseItem{
     public id:string;
     constructor(id:string) {
        this.id =id;  
     }
} 

abstract class ConfigMixin<K extends BaseItem>{
        public saveConfig() {
            const repo = getRepository(Entity);
            repo.update(
                { 
                    id: this.id // Typescript error
                },
                {
                    ...this.getConfig(),
                },
            );
        }
}

class BaseDevice extends BaseItem{
     constructor(id:string) {
        super(id);   
     }
} 
export interface BaseDevice extends ConfigMixin<BaseDevice> {}
applyMixins(BaseDevice , [ConfigMixin]);

但是我收到以下错误: TS2339:属性 'id' 在类型 'ORCASmartLightConfig' 上不存在。

我可以想到两个办法:

  1. 坚持对mixin的严格封装。mixins应该是自立的,不知道它们将混入何处。这意味着mixin不应该知道它已混合到具有 id 字段的 class:
// The first approach sticks to the strict encapsulation of mixins
export abstract class ConfigMixin {
  // Your mixin will receive all the things it needs as parameters
  // so every time you call saveConfig you need to pass the id
  public saveConfig(id: string) {
    console.log(id);
  }
}

// The base class
class BaseItem {
  constructor(public id: string) {}
}

// An implementation of subclass of BaseItem
export class BaseDevice extends BaseItem {}

// Here we tell TypeScript that BaseDevice has ConfigMixin mixed in
export interface BaseDevice extends ConfigMixin {}

// And finally we apply the ConfigMixin
applyMixins(BaseDevice, [ConfigMixin]);

Link to TypeScript playground

  1. 技巧 TypeScript! 在这种情况下,生成的代码与您原来的方法更相似,但它有一个缺点:
// The second approach makes use of an abstract class field
export abstract class ConfigMixin {
  public abstract id: string;

  public saveConfig() {
    console.log(this.id);
  }
}

// The base class
class BaseItem {
  constructor(public id: string) {}
}

// An implementation of subclass of BaseItem
export class BaseDevice extends BaseItem {}

// Here we tell TypeScript that BaseDevice has ConfigMixin mixed in
export interface BaseDevice extends ConfigMixin {}

// NOW THE DRAWBACK
//
// Unfortunately with this approach TypeScript will not complain when
// you are trying to mixin ConfigMixin with a class that does not have id
export class SomeDevice {}
export interface SomeDevice extends ConfigMixin {}

// And finally we apply the ConfigMixin
applyMixins(BaseDevice, [ConfigMixin]);
applyMixins(SomeDevice, [ConfigMixin]);

Link to TypeScript playground