【发布时间】:2021-02-15 15:34:39
【问题描述】:
我有以下代码
type GConstructor<T = {}> = new (...args: any[]) => T;
class Sprite {
name = "";
x = 0;
y = 0;
constructor(name: string) {
this.name = name;
}
setPos(x:number, y:number) {
this.x = x;
this.y = y
}
}
type Positionable = GConstructor<{ setPos: (x: number, y: number) => void }>;
function Jumpable<TBase extends Positionable>(Base: TBase) {
return class Jumpable extends Base {
jump() {
this.setPos(0, 20);
}
};
}
const JumpableSprite = Jumpable(Sprite);
function hi(x: JumpableSprite) {
return 4;
}
问题是我得到了这个错误
'JumpableSprite' refers to a value, but is being used as a type here. Did you mean 'typeof JumpableSprite'?
Parameter 'x' of exported function has or is using private name 'JumpableSprite'.
我很确定我不想要typeof JumpableSprite,因为我希望它输入为JumbableSprite 而不是JumbableSprite 的类。
有没有办法使用 JumpableSprite 作为类型?
【问题讨论】:
-
对于
Jumpable函数,您将返回一个类。尝试为适合参数x的类型的 Jumpable 返回类型创建一个类型 -
这行得通吗?类型 JumpableSprite = Sprite & {jump(): undefined};
-
如果这就是我所需要的,您能否将其发布为答案以便我接受?我认为这是正确的
-
另外,对不起,如果这是一个非常愚蠢的问题。我非常了解 JavaScript,但我对 TypeScript 还是很陌生,所以我已经能够弄清楚大多数事情。我认为使用像这样的类型隐藏名称将解决我遇到的大部分问题。谢谢!
-
我一直在我的项目中尝试这个,它似乎正在工作!唯一的问题是,当我定义一个我已经拥有类的类型时,我收到了一个已经定义的 eslint 消息。这可以修复吗?
标签: typescript mixins