gpt4 book ai didi

TypeScript mixin 受限于另一个 mixin

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

我正在使用 Typescript 2.2 的 mixin,并且想使用另一个 mixin 的属性。

文档显示可以将 mixins 限制为仅混合到某些类中......

const WithLocation = <T extends Constructor<Point>>(Base: T) =>
class extends Base {
getLocation(): [number, number] {
return [this.x, this.y];
}
}

是否可以限制它们只混入包含另一个混入的类?

最佳答案

是的,这是可能的。定义您的其他 mixin,以便它由接口(interface)支持。例如:

interface Named {
name: string;
}

function Named<T extends Constructor<{}>>(Base: T) {
return class extends Base implements Named {
name: string;
};
}

然后您可以在 Constructor 类型参数的交集类型中使用该接口(interface):

const WithLocation = <T extends Constructor<Point & Named>>(Base: T) =>
class extends Base {
getLocation(): [number, number] {
console.log(this.name); // compiles
return [this.x, this.y];
}
};

const NamedPointWithLocation = WithLocation(Named(Point));
const PointerWithLocation = WithLocation(Point); // error, expects argument to be Named

您可以看到一个更复杂的例子来完成 here这将在使用声明文件进行编译时起作用。

关于TypeScript mixin 受限于另一个 mixin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44074357/

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