typescript - 如何在 typecipt 中使用带有 mixins 的类作为类型
问题描述
我有以下代码
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
notJumbableSprite
的类。
有没有办法使用 JumpableSprite 作为类型?
解决方案
正如@tsecheukfung01 在评论中解释的那样,您所要做的就是创建一个与引用类的变量同名的类型。完成此操作后,您将看到 @typescript-eslint 错误(当然,如果您的项目中有 @typescript-eslint)。根据@typescript-eslint 文档,您应该只使用 eslint 忽略行。完整的工作代码...
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);
// eslint-disable-next-line @typescript-eslint/no-redeclare -- intentionally naming the variable the same as the type
type JumpableSprite = Sprite & {jump(): undefined};
function hi(x: JumpableSprite) {
return 4;
}
推荐阅读
- python - 最后除以组的第一行
- python - 在python中优化输出有约束的输入
- python - 从 Django 服务器一次流式传输多个文件
- android - CameraX - 查找 android 设备的焦距
- mysql - 在mysql中查找用户属于哪个百分位组
- python - 具有至少 k 个点的 Numpy 查找区间
- google-tag-manager - 我可以通过控制台将数据添加到数据层来测试 GTM 数据层(goole 标签管理器)吗
- mysql - MySQL每隔两列获取前3行
- jquery - 显示和添加有限数量的 div - Gallery / Jquery
- java - Spring-Data Mysql 在数据库中找不到名称