gpt4 book ai didi

typescript - mixin类的类型是什么

转载 作者:搜寻专家 更新时间:2023-10-30 21:38:07 26 4
gpt4 key购买 nike

我不知道如何在不诉诸一些 hack 的情况下获取 typescript mixin 类的类型(如下所示)

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

function MyMixin<T extends Constructor>(BaseClass: T) {
return class extends BaseClass {doY() {}}
}

// Option A: Ugly/wasteful
const MixedA = MyMixin(class {doX() {}});
const dummy = new MixedA();
type MixedA = typeof dummy;

class OtherA {
field: MixedA = new MixedA();
a() {this.field.doX(); this.field.doY();}
}

// Option B: Verbose
class Cls {doX() {}}
interface MixinInterface {doY(): void}

const MixedB = MyMixin(Cls);
type MixedB = Cls & MixinInterface;

class OtherB {
field: MixedB = new MixedB();
a() {this.field.doX(); this.field.doY();}
}

typescript 不支持诚实的混入/特征让我感到非常难过,但是有没有其他方法可以声明 field 的类型,而无需诉诸 typeof 实例或不必重新声明接口(interface)中的签名(我尝试了 typeof(new MixedBaseA()) 但 typeof 不接受任意表达式)?

最佳答案

可能不是您想要的,但这里有一个不那么浪费的替代方案。给定定义:

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

function MyMixin<T extends Constructor>(BaseClass: T) {
return class extends BaseClass {
doY() { }
}
}

const MixedA = MyMixin(class { doX() {} });

您可以使用以下方法获取类型:

function getReturnType<R>(fn: (new(...args: any[]) => R)): R {
return {} as R;
}

const dummy = getReturnType(MixedA);
type MixedAType = typeof dummy;

const mixedA : MixedAType = new MixedA();
mixedA.doX();
mixedA.doY();

Playground

获取任何表达式类型的提案仍在讨论中:https://github.com/Microsoft/TypeScript/issues/6606 .这将摆脱虚拟变量和函数。

或者,要获得干净的type MixedAType = MyMixinY & X,您可以选择在 mixin 中返回正确的构造函数类型:

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

interface MyMixinY {
doY()
}

function MixinY<T extends Constructor>(BaseClass: T)
: Constructor<MyMixinY> & T {

return <any> class Y extends BaseClass implements MyMixinY {
doY() {
console.log("in Y");
}
}
}

const MixedA = MixinY(class X {
doX() {
console.log("in X");
}
});

function getReturnType<R>(fn: (new(...args: any[]) => R)): R {
return {} as R;
}

const dummy = getReturnType(MixedA);
type MixedAType = typeof dummy; // now is `type MixedAType = MyMixinY & X`

const mixedA: MixedAType = new MixedA();
mixedA.doX();
mixedA.doY();

关于typescript - mixin类的类型是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47732015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com