如何检查类是否在 TypeScript 中应用了 mixin? (推断其类型)

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

我正在尝试确定 TypeScript 类是否以缩小其类型(用于自动完成/智能感知)的方式应用了特定的 mixin,但我遇到了一些困难。我尝试了两种不同的方法,但都没有成功。

Option 1 (link to playground): 在 mixin 中为类添加一个名称。这种方法不起作用,因为类不是在 mixin 内部定义的,而是在调用 mixin 时定义的。结果

instanceof
不认。这是代码:

class A { }

let BMixin = (superclass: any) => class B extends superclass {
  bProp: string = "bProp";
  bMethod() {
    console.log("method from B");
  }
};

const C = BMixin(A)
const c = new C;
console.log(c instanceof B) // Cannot find name 'B'

选项 2(游乐场链接):创建一个接收类并返回混合的实用程序。这种方法的问题是 (a) 我必须找到一种方法来复制所有方法和属性,并且 (b)

instanceof
一直返回 false。这是代码:

class A { }

class B {
  bProp: string = "bProp";
  bMethod() {
    console.log("method from B");
  }
}

function defineMixin (mixinClass: any) {
  return (arg0: any) => class extends arg0 {
    // Here I should do some magic to copy the methods and properties
  }
}

const D = defineMixin(B)(A)
const d = new D;
console.log(d instanceof B) // false

我发现 这篇文章 其中 @elias-schablowski 获取结果类的类型以具有 mixin 的方法和属性。然而,Typescript 编译器并不真正了解原型链,因此你不能缩小任意类的类型。

换句话说,我希望能够做到:

if (something instanceof someMixin) {
    // here I want "something" to have the autocomplete
    // with all the properties and methods of "someMixin".
}

我还发现

ts-mixer
库提供了一个替代
instanceof
的函数,称为 hasMixin 来满足这个目的。 问题是这个库(~2kb GZipped)以非常复杂的方式修改了基类原型,并且只能在某些限制下工作。例如,我知道
this
super
不能使用 👎.

我想要一个更简单的解决方案,具有链接原型的所有好处,而无需以某种奇怪的方式修改它们。

我该怎么做?我将不胜感激任何帮助。

typescript mixins
© www.soinside.com 2019 - 2024. All rights reserved.