【问题标题】:Typescript casting problem on object with getters and setters带有getter和setter的对象的Typescript转换问题
【发布时间】:2019-03-05 07:51:00
【问题描述】:

我对以下代码有疑问。我认为是一个铸造问题,但我不知道如何解决它。

interface Code {
  code: string;
  expiration: number;
}

interface IActivationCode {
  [userId: string]: Code;
}
const activationCode: IActivationCode = {
  set userId(id: string) {
    this[id] = {
      code: Math.random()
        .toString(36)
        .substring(7),
      expiration: new Date().setMinutes(new Date().getMinutes() + 30)
    };
  },
  get userId() {
    return this.id;
  }
};

您可以在此处复制代码以查看问题。 TypeScript Playground

【问题讨论】:

  • 打字机游乐场链接实际上不起作用。无论如何,错误是您试图将字符串强制转换为“代码”。您的 rinterface 将userId 的返回类型显式定义为Code,而您返回的是string(并且setter 接受一个字符串)。

标签: javascript typescript casting


【解决方案1】:
    interface Code {
  code: string;
  expiration: number;
}

interface IActivationCode {
  [userId: string]: Code;
}
const activationCode: IActivationCode = {
  set userId(id: Code) {
     id = {
      code: Math.random()
        .toString(36)
        .substring(7),
      expiration: new Date().setMinutes(new Date().getMinutes() + 30)
    };
  },
  get userId() {
    return this.id;
  }
};

更改 userId 的类型将消除代码中的错误,但我仍然对您要实现的目标感到困惑。

【讨论】:

  • idthis[id] 大不相同。在您的示例中,this.id 将始终未定义,因为它未在设置器中分配。但是,如果您尝试分配它,它将引发错误,因为您无法分配具有 Code 类型的对象属性。
  • 如果我运行 activationCode.userId = "myId"; 我会得到这样的结果:{ myId: { code: 'vwurul', expiration: 1551775465464 } } 我想根据用户 ID 生成一个随机字符串,该字符串是激活密钥和该密钥的到期日期跨度>
猜你喜欢
  • 2016-07-01
  • 1970-01-01
  • 2019-01-12
  • 1970-01-01
  • 1970-01-01
  • 2019-08-28
  • 1970-01-01
  • 2012-06-23
  • 1970-01-01
相关资源
最近更新 更多