【问题标题】:How to use classes with mixins as types in typescipt如何在 typescript 中使用带有 mixins 的类作为类型
【发布时间】: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


【解决方案1】:

正如@tsecheukfung01 在 cmets 中解释的那样,您所要做的就是创建一个与引用类的变量同名的类型。完成此操作后,您将看到 @typescript-eslint 错误(当然,如果您的项目中有 @typescript-eslint)。根据@typescript-eslint docs,您应该只使用 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;
}

【讨论】:

    猜你喜欢
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 2021-03-15
    • 2018-02-19
    • 1970-01-01
    • 2018-09-05
    相关资源
    最近更新 更多