TypeScript 混合限制为不同 类
TypeScript mixin constrained to different classes
我想构建一个 mixin 并将其应用于不同的 类(在本例中为 "Sprite" 和 "Graphics")。
第三行不工作:
function Animated<T extends Constructor<Sprite> | Constructor<Graphics>>(Base: T) {
TypeScript 抱怨 "T is not a constructor function".
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
我想构建一个 mixin 并将其应用于不同的 类(在本例中为 "Sprite" 和 "Graphics")。
第三行不工作:
function Animated<T extends Constructor<Sprite> | Constructor<Graphics>>(Base: T) {
TypeScript 抱怨 "T is not a constructor function".
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