typescript - TypeScript mixin 受限于不同的类
问题描述
我想构建一个mixin并拥有它,以便它可以应用于不同的类(在本例中为“Sprite”和“Graphics”)。
第三行不起作用:
function Animated<T extends Constructor<Sprite> | Constructor<Graphics>>(Base: T) {
TypeScript 抱怨“T 不是构造函数”。
import { Sprite, Texture, Container, Graphics } from "pixi.js";
type Constructor<T = {}> = new (...args: any[]) => T;
function Animated<T extends Constructor<Sprite> | Constructor<Graphics>>(Base: T) {
return class extends Base {
constructor(...args) {
super(...args);
}
animate() {
console.log('animte it');
}
}
}
export class AnimatedSprite extends Animated(Sprite) {
constructor(texture? : Texture) {
super(texture);
}
}
export class AnimatedContainer extends Animated(Graphics) {
constructor(nativeLines?: boolean) {
super(nativeLines);
}
}
解决方案
好的,找到了解决方案:
export interface IAnimated {
animate():void;
}
export const AnimatedSprite: Constructor<IAnimated> & typeof Sprite = <any>Animated(Sprite);
export const AnimatedGraphics: Constructor<IAnimated> & typeof Graphics = <any>Animated(Graphics);
稍后(使用):
let s = new AnimatedSprite(someTexture); // has type "Sprite" and also interface IAnimated
let g = new AnimatedGraphics(false); // has type "Graphics" and also interface IAnimated
推荐阅读
- python - s3fs 突然停止在 Google Colab 中工作,出现错误“AttributeError: module 'aiobotocore' has no attribute 'AioSession'”
- pdf - PDF 输出中的半透明元素之间出现不需要的线条(使用 puppeteer 生成)
- javascript - 我如何在 Babylonjs 中自动旋转免费相机?
- android - 单元测试在一次运行时失败,但在我单独运行时通过
- css - 是否可以在悬停时转换 CSS 网格内单个项目的伪元素?
- r - 如何在 R Shiny 中的 SelectInput 选项中动态更新列名
- scroll - 如何通过拖动滚动条来滚动 EditText 的内容?
- vue.js - VueJS 路由器 - 使用子路由更改根目录中的命名视图
- c# - 等效于 C# .Net 中的 setPixels(int [] pixel, int offset, int stride, int x, int y, int width, int height)?
- javascript - 如何让浮动文本跟随鼠标悬停在 Two.js 创建的元素上的光标?