【发布时间】: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